Home > Software engineering >  React native adding object to state
React native adding object to state

Time:03-04

Testing some things in React and having some issues with some of my logic. I am trying to get value from inputs in a form then on submitting that form I want to take that object of input values and add them to my plant state. When I console log I get the state values but then the plant state is empty. Any help is appreciated.

Thank you

    const initialState = {
        id: null,
        TypeofPlant: "",
        Phase: "",
        Days: 0,
        Start: 0,
        End: 0,

      };

  const [plant, setPlant] = useState(initialState);
      const [TypeofPlant, setType] = useState('')
      const [Phase, setPhase] = useState('')
      const [Days, setDay] = useState(null)
      const [Start, setStart] = useState(0)
      const [End, setEnd] = useState(0)
    
        setType(...TypeofPlant)
        setPhase(...Phase)
        setDay(...Days)
        setStart(Start)
        setEnd(End)
       
        var data ={
       
            TypeofPlant: TypeofPlant,
            Phase: Phase,
            Days: Days,
            Start: Start,
            End: End,

        }
      
            DataService.addNewPlant(data).then(response => {
              
                setPlant({
                    TypeofPlant: response.data.TypeofPlant,
                    Phase: response.data.Phase,
                    Days: response.data.Days,
                    Start: response.data.Start,
                    End: response.data.End,
               
                
                })
               
                console.log(response.data);},
                (error) => {
                    console.log(error)
                }
            );

CodePudding user response:

Try to console plant outside of DataService block.

CodePudding user response:

The Response.json() method interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON.

Update your code like below and try

....
DataService.addNewPlant(data).then(res => {
            const response = res.data.json();
            setPlant({
                TypeofPlant: response.TypeofPlant,
                Phase: response.Phase,
                Days: response.Days,
                Start: response.Start,
                End: response.End,
            })
            console.log(response);}
....
  • Related