1

I wanted to display the array series and when I tried to console the array this.state.series in the function it does has the result and the value inside but when I render this.state.series just keep giving empty array. I wonder is it because of the componentDidMount()?

constructor(props){
        super(props);
        this.state={series:[]}
      }

    GetTransaction=()=> {
       
        var APIURL="http://10.0.2.2:80/api/getTransaction.php";

        var headers={
            'Accept':'application/json',
            'Content-Type':'application.json'
        }


        fetch(APIURL,
            {
                method:'POST',
                headers: headers,
                
            })
        .then((response)=>response.json()) 
        .then((response)=>
        {
            
            this.setState({results:response});
            
             this.state.results[0].map((a) => {
                
            this.state.series.push(a.count)
            });
            
            console.log(this.state.series)
        })   
        .catch((error)=>
        {
            alert("Error"+error);
        }
        ) 
       
       
    }
    
    componentDidMount(){ // runs after the component output has been rendered to the DOM
        this.GetTransaction();
    }
    

    render(){
          
        console.log(this.state.series)
        

output

Array []
Array []
Array []
Array []
Array []
Array []
Array []
Array [
  "1",
  "2",
  "1",
  "1",
]

2 Answers 2

1

There are basically 2 errors in GetTransaction state assignment:

  1. you can't read a state just assigned because this.setState is async. If you want to get the very last value of state you should use this.setState's callback:

    this.setState({results:response}, () => {
       console.log(this.state.result); //<-- here you have the very last value of result
    });
    
  2. state must be always setted with this.setState: this.state.series.push(a.count) is not good.

So you have to rewrite your code in this way:

        ...
        this.setState({results:response}, () => {
            let seriesAppo = [];
            this.state.results[0].map((a) => {
                seriesAppo.push(a.count);
            });
            this.setState({series: seriesAppo}, () => {
               console.log(this.state.series);
            })      
        });
        ...
         
Sign up to request clarification or add additional context in comments.

3 Comments

may I know why there are empty array before the array with value?
@Unknown if you mean why state array is empty and after a while will be filled is because GetTransaction makes a fetch (so it takes time to response and in this time state is empty). Then fetch returns value and you call setState but also this is async and takes time to set state. Finally the state will be filled and you start to see correct values. Is just a matter of async calls that, as I told you, are taking time to be resolved. It's totally normal.
@Unknown No problem. Have a nice coding =)
1

That‘s weird

   this.state.results[0].map((a) => {                
     this.state.series.push(a.count)
   });

Don‘t manipulate state that way, only with setState.

      const series = response[0];
      this.setState({series: series});

Even if you wanna add elements to an array you have to recreate the array. You can achieve this as follows:

     const series = response[0];
     this.setState({series: […this.state.series, …series]});

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.