Skip to content
Advertisement

Cannot destructure an object

I fetched and object which contains two properties, one is a number and one is an array. So I right away accessed the array and then assigned to a state and then passed each item to another component through context api. And it does not working. Here is my code:

const [info, setInfo] = useState([]);
const [i, setI] = useState(0);

const fetchUrl = async() => {
    setLoading(true);
    const response = await fetch(url);
    const data = await response.json();
    setInfo(data.results);
    setLoading(false);
} 

useEffect(() => {
    fetchUrl();
}, []);

const {correct_answer, incorrect_answers, question} = info[i];
const arr = [correct_answer, ...incorrect_answers].sort((a, b) => a.length - b.length);

In this code ‘correct_answer’ is a string and ‘incorrect_answers’ is an array. After running this code it says:

TypeError: Cannot destructure property ‘correct_answer’ of ‘info[i]’ as it is undefined.

And sometimes it says:

TypeError: ‘incorrect_answers’ is not iterable.

How do I fix this problem?

Advertisement

Answer

You’re trying to desctructure an array element that doesn’t exist yet. You can use this workaround:

const {correct_answer, incorrect_answers = [], question} = info[i] || {};

Note that that properties equal undefined until you get response from the api. Also here you can see that I assigned a default value to incorrect_answers property so it could be spread in the further code.

Advertisement