1

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> 
1
  • No just text ["item one", "item two"] Commented May 3, 2022 at 20:22

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.