'React using fetch returns undefined after refreshing the page
When I try to get information from the api and retrieve it into a scroll list, at first retrieval is successful, but when the page is refreshed, an error message is received under inspect: "Uncaught TypeError: response is null". How can this issue be resolved? The api I'm using: https://opentdb.com/api_category.php
Thank you.
axios.defaults.baseURL = "https://opentdb.com";
const GetApiData = ({ url }) => {
const [response, setResponse] = useState(null);
const [error, setError] = useState("");
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async() => {
await axios
.get(url)
.then((res) => setResponse(res.data))
// console.log('cccc')
.catch((err) => setError(err))
.finally(() => setLoading(false));
};
fetchData();
}, [url]);
return { response, error, loading };
Here i call it, the problem is with the line :
<FieldOptions options={response.trivia_categories} label="Category" />
const { response, error, loading } = GetApiData({ url: "/api_category.php" });
return (
<form >
<FieldOptions options={response.trivia_categories} label="Category" />
<FieldOptions options={difficultyOptions} label="Difficulty" />
<FieldOptions options={typeOptions} label="Type" />
<TextField id="filled-basic" label="How many questions?" variant="outlined" type="number" onChange={handleChange}/>
<Box mt={3} width="100%">
<Button fullWidth variant="contained" type="submit">
Get Started
</Button>
</Box>
</form>
)
}
Solution 1:[1]
Is it because you're initializing response to null in your useState hook?
const [response, setResponse] = useState(null);
If you try to access the response variable before it gets set by your API fetch, it will be the value of null.
You can try initializing it to a different value such as an empty object. This might work depending on how you access the variable when your component initially renders.
const [response, setResponse] = useState({});
Or, you can check if response is not null before accessing it.
if (response !== null) {
// code
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
