S
S
szQocks2021-06-13 16:44:41
React
szQocks, 2021-06-13 16:44:41

Why does an imported component fire faster than a hook in React?

Code in App.js main component

const instance = axios.create({
baseURL: env.API_URL
});

const [todos, setTodos] = useState();

const getAllTodos = () => {
instance.get()
.then(res => setTodos(res.data))
.catch(err => console.log(err))
};

useEffect(() => getAllTodos(), []);

And in the same App component, I import the TodoList component and pass the todos state into it (that is, the data received when requested through the useEffect hook that calls the getAllTodos function.
And the problem is that I do not have time to get the data as I already get an error from the TodoList component
about the fact that todos is undefined when calling the map methods (that is, when rendering). I solved this problem in a hack by using the question operator before the dot in the TodoList component.

todos?.map

Even if I solved this problem with a crutch... I still don't understand why the component tries to render todos faster than the useEffect hook in the parent component fires?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2021-06-13
@szQocks

Because the components themselves do not wait for anyone and are rendered synchronously , i.e. "right now", and the response from the server comes asynchronously , i.e. "sometime later". Moreover, the hook useEffectitself only runs after rendering.
There are two options:
1. Set the default state:
const [todos, setTodos] = useState([]);.
First it will show an empty list, then a loaded one.
2. Do not render the component until there is no data needed for it:

{todos ? <TodoList todos={todos}/> : <LoadingComponent/>}
First, a spinner will show a thread, then a loaded list.

K
Kentavr16, 2021-06-13
@Kentavr16

Make getlaatodos an async function with try and catch. This should help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question