I have a function that grabs data from a local JSON file and renders it. Simple stuff. I do the fetch request within the useEffect hook to fire it only on the first render. Once the data is fetched, it sets it in employees. Once in employees, I use another useEffect to set some other states with data from employees.
const [employees, setEmployees] = useState<any>([]) const [firstNames, setFirstNames] = useState<any>([]); useEffect(() => { fetch(“data.json”, { headers: { “Content-Type”: “application/json”, Accept: “application/json”, }, }) .then(function (response) { return response.json(); }) .then(function (data) { setEmployees(data[“employees”]); }); }, []); useEffect(() => { console.log(employees) first_names_array = employees.map(emp => emp[“first_name”]) console.log(first_names_array) setFirstNames(first_names_array) }, [employees]); /*render list of employees*/
This is the output of employees when I console.log it
[ { “first_name”: “John”, “last_name”: “Doe”, }, { “first_name”: “Jane”, “last_name”: “Doe”, }]
And the output of console logging first_names_array
[‘John’, ‘Jane’]
And this is the error I get
Unhandled Rejection (TypeError): Cannot use ‘in’ operator to search for ‘options’ in John
Why can I not set my state? I have an array of strings (first_names_array) and I should be able to just simply set it with setFirstNames but it’s not working
submitted by /u/_malawax_
[link] [comments]