Home > OS >  React.useState Hook only displaying length of object, not object itself
React.useState Hook only displaying length of object, not object itself

Time:03-31

Basically, I have a component named Upload:

const Upload = () => {
    const [scene , setScene] = React.useState([]);

    // handleUpload = (event) => {
    //     console.log('Success!');
    // }


    function renderHandler(s){
      console.log('[RENDER] calling...')
      console.log(s);

      if(scene.length == 0){
        console.log('[RENDER] Denied!')
        return(
          <div>
            Nothing is rendered..
          </div>
        )
      } else {
        console.log('[RENDER] Working...')
        console.log('[RENDER] Received planes:');
        console.log(blockState);
        console.log(scene);

        return (
          <View top={blockState}/>
        )
      }
    }

    function parseNBT(input) {
      setScene(scene.push('1'));
      setScene(scene.push('2'));
      console.log('scene:');
      console.log(typeof scene);
      console.log(scene);
      console.log('\n blockState:');
      console.log(typeof blockState);
      console.log(blockState)



    }
     return (
    <Container>
    Input NBT file <br/>
    <input type="file" onChange={handleChange}></input>
    {renderHandler(scene)}
    </Container>
  )
}

The issue here is, when I'm setting the scene's state in parseNBT, and console log scene, it gives me the array:

parsenbt

However, when I call it from renderHandler, it simply returns the length of the array, in this case it was 2 renderhandler weird

Very weird, maybe i'm missing something?

CodePudding user response:

The .push returns the length of the array.

Return value
The new length property of the object upon which the method was called.


Try

  setScene( currentScene => [...currentScene, '1'] );
  setScene( currentScene => [...currentScene, '2'] );

CodePudding user response:

To summerize briefly, you are treating 'scene' as a mutable object, when it is immutable. Meaning, when you are trying to do a 'scene.push' it is trying to modify an immutable object. A regular array is mutable, but not a react state array. Therefore, you do not want to give an update to scene directly, you want to take its previous state, concatenate it with your new desired value, then make that new value your new state.

Like so:

Replace your lines:

  setScene(scene.push('1'));
  setScene(scene.push('2'));

with:

 setScene((scene) => [...scene, 1]);
 setScene((scene) => [...scene, 2]);
  • Related