Home > front end >  How to get data to show up on useState?
How to get data to show up on useState?

Time:11-25

const { recipeId } = useParams();

const { loading, data } = useQuery(QUERY_SINGLE_RECIPE, {
    variables: { recipeId: recipeId },
});

// THESE CODES HERE SHOULD GRAB THE RECIPE AND LOAD THE PRESET DATA
// INTO THE RESPECTFUL AREAS OF THE FORM
const recipe = data?.recipe || {};
// console.log('recipe');
// console.log(recipe);

let ingredientList = [''];
if (recipe?.ingredients) {
    for (let a = 0; a < recipe.ingredients.length; a  ) {
        ingredientList  = (recipe.ingredients[a]   '\r\n');
        // console.log(ingredientList);
    }
}

let directionList = [''];
if (recipe?.directions) {
    for (let b = 0; b< recipe.directions.length; b  ) {
        directionList  = (recipe.directions[b]   '\r\n');
        // console.log(directionList);
    }
}

// THESE NEXT CODES SHOULD, IN MOST BASIC TERMS, USE A USESTATE TO BASICALLY 
// CREATE AN UPDATED RECIPE. SHOULD HAVE THE SAME CODE AS THE ADD/CREATE NEW RECIPE
const [updateRecipe, setUpdateRecipe] = useState({
    title: recipe.title,
    category: recipe.cateogry,
    servings: recipe.servings,
    totalTime: recipe.totalTime,
    ingredients: recipe.ingredients,
    directions: recipe.directions,
    imageid: recipe.imageid
});

When console logged, updateRecipe comes up as an object with undefined, how do I get the update recipe to show the object that will later be updated in a form?

CodePudding user response:

The issue you have is that you are not reacting to the state update. If I'm not mistaken (I don't see which libraries you're using), the useQuery is requesting something from a GQL API. data would be a reactive variable, for which you would have to use the useEffect hook to react to this change. So if you add

useEffect(()=>{
 console.log(data)
},[data]);

You should get the data once it's fetched from the server, and update the state within the useEffect callback function.

  • Related