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

Time:12-29

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>
)
}
     

CodePudding user response:

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([])

  • Related