I'm attempting to get data from an array from ComponentOne to ComponentTwo. The state lives in App.js. This is sort of working as I can see the data when console.logging from ComponentTwo. However the data does not show on screen with the <p> {props.PhaseThreeItems[0] } </p>
code.
Two questions:
#1: Am I going about this the correct way?
#2: Why is the data not showing on screen?
// App.js:
const [phaseThreeArray, setPhaseThreeArray] = useState([])
<ComponentOne PhaseThreeArrayProp={phaseThreeArray}/>
<ComponentTwo PhaseThreeItems={phaseThreeArray}/>
...
// ComponentOne
const checkInput = () => {
props.PhaseThreeArrayProp.push("my data");
}
...
// ComponentTwo
const showData = () => {
console.log(props.PhaseThreeItems[0])
}
<p> {props.PhaseThreeItems[0] } </p>
CodePudding user response:
React ... reacts... to state changes. This means that you have to tell react "this has updated", via your setPhaseThreeArray
property. What you have done is manually call push
, rather than setting the state. React isn't aware of any data changes, and as such, doesnt update.
To fix this, you need to set the state using the function. The quickest way of doing it would be:
// App.js:
const [phaseThreeArray, setPhaseThreeArray] = useState([])
<ComponentOne setPhaseThreeArray={setPhaseThreeArray} PhaseThreeArrayProp={phaseThreeArray}/>
<ComponentTwo PhaseThreeItems={phaseThreeArray}/>
// ComponentOne
const checkInput = () => {
props.setPhaseThreeArray([...props.PhaseThreeArrayProp, "my data"])
}
This will set the state with the new array.