0

I'm new to react and i'm trying to use hooks for my project. I need to pass an array from parent to child, just that when I put the array in the props it just pass its length.

ParentComponent.js
export default function NewHome() {

const [isReady, setReadyState] = useState(false);

const [regionWithValue, setRegionWithValue] = useState([]);


function getRegion() {
    fetch("http://localhost:3000/region")
        .then(res => res.json())
        .then(
            (result) => {
                result.forEach((el) => {
                    setRegionWithValue(regionWithValue.push(el));
                })
                setReadyState(true);
            },
            (error) => {
                setErrore(true);
            }
        );
};
useEffect(() => {
    getRegion();
    console.log(regionWithValue);
    // eslint-disable-next-line react-hooks/exhaustive-deps
},[]);
if (ReadyState) {
console.log(regionWithValue);
return(
<ChildComponent region={regionWithValue}/>
)
}

The console.log in useEffect() actually print the correct array with data fetched, but the second console.log right before the return, just print out the array size, so I can't pass it to the ChildComponent. I don't know if is cause lifecycle so I'm getting all wrong. Thank you.

skyboyer
  • 22,209
  • 7
  • 57
  • 64

2 Answers2

0

This is the problem:

setRegionWithValue(regionWithValue.push(el));

push returns the length and not the array you pushed to

You can do it like this:

setRegionWithValue(v => ([...v, el]));

See: Why does Array.prototype.push return the new length instead of something more useful?

Stating from Array.prototype.push() MDN docs:

The push() method adds one or more elements to the end of an array and returns the new length of the array.

vsync
  • 118,978
  • 58
  • 307
  • 400
-1

You cant use push on a React Hook. You need to get the previous state and add to that state (prevState is the industry standard naming convention) . This can be accomplished in your fetch like this:

    setRegionWithValue(prevState => (
          setRegionWithValue([...prevState, result])
        ));

This will always add to the state, if you want to just create a new state everytime you fetch then you should just use:

setRegionWithValue(result)

Keaton Benning
  • 471
  • 5
  • 13
  • this is incorrect. the `push` method has nothing to do with the *React Hook*. This problem is javascript-related and not React-related – vsync Jan 11 '21 at 18:11
  • its the exact same answer as below... LOL ... it is correct, and as i said the push method should not be used on react hooks. – Keaton Benning Jan 11 '21 at 18:13
  • Also since hooks are only on React, it is 100% react related and not javascript related – Keaton Benning Jan 11 '21 at 18:14