Search code examples
arraysreactjsreact-hooksuse-effect

React - Array are passed as their length


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.


Solution

  • 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.