I am abit confused with react getting api why i always have to use optional operator while fetching data to react element
here is an example :
const [data, setData] = useState();
const getData= async (e) => {
try {
const { data } = await axios.post("/data", {}, { withCredentials: true });
setData(data)
} catch (err) {
console.log(err)
}
};
useEffect(() => {
getData();
},[])
return (
// why i always have to use ?. to display the data ?
{data?.restData.map(el => {
return <div>{el.name}</div>
})}
)
why I have to use ?. to be able to display the data or I receive an error that the data is undefined, is there a better way to display data?
because when I run the app I get 2 console logs the first one is undefined and then the data , Am I missing something ?
CodePudding user response:
Because your data
could be undefined. When you initialse the state, data
is actually undefined. Without the ?.
it would throw an error, that data
is undefined. Now it would just do nothing.
CodePudding user response:
const [data, setData] = useState();
Your initial state is undefined. So if you tried to do data.restData
, you would throw an exception, because undefined
does not have a restData
property. using ?.
is a very simple way to handle that case.
If you prefer to do something more complicated, you could do that too, which may or may not use optional chaining. For example:
if (!data) {
return <div>Loading...</div>
} else {
return (
<>
{data.restData.map(el => {
return <div>{el.name}</div>
})}
</>
);
}
CodePudding user response:
You can set your initial state first:
const [data, setData] = useState({restData: []});
Then you can write:
data.restData.map...
CodePudding user response:
Because initial state is undefined, if you don't wanna use ?.
define the initial state:
const [data, setData] = useState({restData: []});