I'm very new to react so apologies if this question has already been answered or should be phrased differently. I have a functional component that fetches a .json file from my public folder in an async function (loadData()). Using the developer tools in my chrome window, I can see that the function gets me exactly what I want, yet the state doesn't seem to want to update when I use setData.
Edit:
So I think I know what the problem is, which is that the first time the component renders, the variable source
needs that JSON object which won't be there until the component re-renders. If that's the case, should all the code starting at let source = pickRandomVerb(data)
go somewhere outside useEffect()?
function ComposedTextField() {
const classes = useStyles();
const [data, setData] = React.useState([]);
const [displayVerb, setDisplayVerb] = React.useState('');
const pickRandomVerb = (list) => {
var obj_keys = Object.keys(list);
var ran_key = obj_keys[Math.floor(Math.random() * obj_keys.length)];
return list[ran_key];
}
const loadData = async() => {
const response = await fetch('verbs.json');
const json = await response.json();
setData(json);
console.log(json); //json is exactly what I want here
console.log(data); //data is just '[]' here
}
useEffect(() => {
loadData();
console.log(data) //data is also '[]' here
let source = pickRandomVerb(data)
let verbSource = source.infinitive;
let showVerb = verbSource.toString().replaceAll("\"", "");
setDisplayVerb(showVerb)
}, [])
return(
<div>
<Typography className = {classes.form}>
<p>{displayVerb}</p>
</Typography>
</div>
)
}
Can anyone let me know what I'm missing? Thanks in advance.