简体   繁体   中英

Pulling Data From Node.js Rest Api Into React with axios

I am New to react, Node.js so I apologize if this is simple. I have been trying to pull Data From A Node.js Api Running Express into a React Component with Axios. I have tried many different ways and have searched for a solution with no luck. I am unable to access the Id as well as the ProductName

JSON DATA

{"Results":
     [
       {"id":4,"productName":"Flap Disc"}, {"id":5,"productName":"Fiber Disc"}
     ]
}

For whatever reason I am unable to Access the data inside these Objects.

CODE

export default function Parent () {
const [products, setProducts] = React.useState('');

const url = 'http://localhost:3040/';

React.useEffect(()=>{
    async function getProduct(){
        const response = await axios.get(`${url}`);
        const a = (response.data.Results)
        setProducts(a.map((item)=> 
        {item}
        ))
    }
    getProduct()
}, [])

return(
    <div>
        {
            console.log(products)
            
        }
    </div>
)
}
     

Logging out inside JSX won't do anything. What you want to do is map over the data and display it as a component. Change your return to something more like this

 return ( <div> {products?.map((product) => <p>{product.name}<p>) </div> )

You should also change the default value fo products from an empty string to an empty array

const [products, setProducts] = React.useState([])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM