I was wondering how it is possible to run a function after you use the useEffect to fetch data, where the function is manipulating the data after its been pulled?
import React, { useState, useEffect } from 'react';
const Result = (props) => {
const [ playerName, setPlayerName ] = useState('');
const [ playerChoice, setPlayerChoice ] = useState(null);
const [ computerChoice, setComputerChoice ] = useState(null);
const [ result, setResult ] = useState(null);
useEffect(() => {
setPlayerName(props.location.state.playerName);
setPlayerChoice(props.location.state.playerChoice);
setComputerChoice(generateComputerChoice);
setResult(getResult())
}, []);
const getResult = () => {
// code that runs after the setting of the playerName and playerChoice. Will return "Win", "Lose", or "Draw"
};
const generateComputerChoice = () => {
const outcomes = [ 'Rock', 'Paper', 'Scissors' ];
return outcomes[Math.floor(Math.random() * outcomes.length)];
};
return (
<div className="app-container">
<strong>YOU {result}</strong>
<br />
<strong>{playerName}</strong> chose <strong>{playerChoice}</strong>
<br />
<strong>Computer</strong> chose <strong>{computerChoice}</strong>
</div>
);
};
export default Result;
So here in this example I grab the playerName and playerChoice from a previous page, and then add that to my useState on page load.
After that I randomly generate the computerChoice.
However, after that I want to use the playerChoice amd computerChoice that has been added to the state and use that to see if the game is a win, lose or draw.
result ends up being null because I assume that by the time the getResult function is called, the states haven't been set yet.
Do you guys know what should be done in this situation? Seems like this could be a common thing considering you might wanna grab data from an API and then do something with that data before wanting to render it.