Search code examples
jsonreactjsaxiosfetch

Data not appearing after axios fetch (ReactJs)


Good day guys, i'm having a little trouble trying to req data from axios and showing it up at ReactJS, i'm able to console.log the data, but when i try to render it at the page, it simply dot not appear, could someone please lend me a hand? i will let the code and a print of the console.log, it's probably a newbie mistake since i'm new to ReactJs and JSON, but i would be very grateful if someone could explain!

Console Log and data not showing

CODE:

import Image from 'next/image'
import { useRouter } from 'next/router'
import React, { Component, useState } from 'react'
import ReactDOM from 'react-dom'
import { useHistory ,useLocation } from 'react-router-dom';
import axios from 'axios'


 

const options = {
    method: 'GET',
    headers: {
      'Authorization': 'OAuth oauth_consumer_key="key",                    oauth_signature_method="PLAINTEXT",   oauth_signature="2CC8D92526EE859C90AABB1F09F3B719&"'}
  };

class Page extends React.Component {

    state= {
        
        motorData: [],
        opa: []
        
    };
   
    componentDidMount() {
        const make = "fiat"
         axios.get(`https://api.trademe.co.nz/v1/Search/Motors/Used.json?make=${make}`, options)
          .then(res => {
            const cars = res.data;            
            console.log(cars)
            this.state.motorData.push(cars.List[0].StartPrice)
            console.log(this.state.motorData)           
            
           
            
          })

          
      }
      
      render() {
        return <div>
            
            Data:{this.state.motorData}
            
            </div>
      }
    
  }
  
  export default Page ```

Thank you guys so much in advance!

Solution

  • Instead of doing a push to your state, you need to use setState. Something like this:

    componentDidMount() {
        const make = "fiat"
        axios.get(`https://api.trademe.co.nz/v1/Search/Motors/Used.json?make=${make}`, options)
            .then(res => {
                const cars = res.data;            
    
                this.setState(state => ({
                    motorData: [...state.motorData, cars.List[0].StartPrice]
                });       
            })
    }
    

    Also, your motorData is an array, right? so in your render method you might want to loop in that array because you won't be able to print it I think. You should do something like this:

    render() {
        return (
            <div>
                
                Data:
    
                // Adjust the return to be what you want it to render and
                // don't forget to add a `key` property to the element you
                // will return
                {this.state.motorData.map(data => data)}
                
            </div>
        )
    }