Reputation: 45
i use axios to retrieve data from back. I do get a result from the back. I can even console.log it. Yet, even I assign it to the recipe variable. It doesn't works. I get a empty array. Anyone would known why ? I really don't understand.
FRONT
import React, { useEffect,useState } from 'react'
import Header from '../../components/Header'
import axios from 'axios'
export default function OneRecipePage(props) {
const [recipe, setrecipe] = useState([])
useEffect(() => {
const id = props.match.params.id
const getRecipe = async () => {
const url = `http://localhost:8000/user/recipe/${id}`
const result = await axios.get(url)
setrecipe(result.data)
console.log('recipe',recipe)
console.log('from back', result.data);
}
getRecipe()
},[])
return (
<div>
<Header/>
<main class="main">
<div class="heading">
<aside class="recipes-info__category_name">{recipe.name}
</aside>
<aside class="recipes-info__date">{recipe.created_at}
</aside>
<h2 class="heading-secondary heading-secondary--big">{recipe.title}</h2>
<p>by author</p>
</div>
<div class="image-box">
<img class="image" src={recipe.photo}/>
</div>
<div class="recipes-details"></div>
</main>
</div>
)
}
BACK
router.get('/recipe/:id', (req,res) => {
const id = req.params.id
connection.query('SELECT * from ETB.recipes WHERE id = ?', id, (err, results) => {
if (err) {
res.status(500).send('Error retrieving the recipe')
}else {
res.status(200).json(results)
}
})
})
Upvotes: 0
Views: 25
Reputation: 1001
In react, set State is an asynchronous aciton. By the time it executes next line, it is no guaranteed that it has set state.
instread of this
`setrecipe(result.data)
console.log('recipe',recipe)`
you can use useEffect()
to detect the change in state.
useEffect(()=>console.log('recipe',recipe),[recipe])
Upvotes: 1