Issue
i am newly startup react native framework here, i am using useState and useEffect to fetch data from api and store in useStete. when i render or try to fetch data from api, at the first log/render is giving me undefined and the it's giving me data for the API. The first undefined is making problem for me, so i want to avoid the first render for fetching data. it's okay for me to give direct second render for the fetch data for API.
so either how can i overcome undefined here wait until give me fetch data or directly provide me second render avoid first render of undefined.
i am really appriciate your helping,
thanks in advance!
Note: i don't want to initialize State to avoid undefined.
const [data, setData] = useState();
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts/5")
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.error(error))
}, []);
console.log(data);
Solution
If you set a default value in the useState: this will be the value before the API request
If you don't set a default value in the useState: the default value before the API request is going to be always undefined
one way around this is to do something as follow:
import React, { useEffect, useState } from "react";
export default function MyComponent() {
const [data, setData] = useState();
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts/5")
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.error(error));
}, []);
if (!data) {
return <React.Fragment></React.Fragment>;
}
console.log(data);
return <MyChildComponent>{data}</MyChildComponent>;
}
Explanation:
if (!data) {
return <React.Fragment></React.Fragment>;
}
if (!data) {
return <></>;
}
if (!data) {
return null;
}
These options are all the same and they help you avoid rendering anything in case no data is available
Answered By - Ali Zgheib
Answer Checked By - - Marie Seifert (ReactFix Admin)