AnotherDaphne / cosi-103a

0 stars 1 forks source link

Sprint 9: Creating New Recipe Page From Input (Adding recipes) #136

Open vbarbieri7 opened 6 months ago

vbarbieri7 commented 6 months ago

Issue: JSON is processed but struggling to output the processed code onto a new page.

– Not sure where to get API URL for UseEffect – How to get correct id of new recipe

(as of this point, JSON entered code shows up on navbar because it is not sent anywhere or linked correctly in our index.js App

yuh2k commented 6 months ago

Hi Victoria could you post code links related to that issue? Just below this thread

vbarbieri7 commented 6 months ago

Hello! This is the link to the addrecipes file that I added to read the JSON code and create a Recipe, but then I got stuck on how to use UseEffect, UseState, and get the id of the recipe to create a new page of that Recipe https://github.com/AnotherDaphne/cosi-103a/blob/recipes---v/recipes/src/pages/addrecipe/addrecipe.js

yuh2k commented 6 months ago

Thanks for the links, regarding how to make use of useEffect to get API, the API URL should come from your backend which should be declared in the server/index.js file.

The api should work on get every recipe's information and return them in a json format, then your frontend can render it.

Here is an example how to call it on front-end.

function App() { const [recipes, setRecipes] = useState([]);

useEffect(() => { fetch('!!PUT YOUR API HERE') .then(response => response.json()) .then(data => setRecipes(data)) .catch(error => console.error('Error fetching data:', error)); }, []);

return (

{recipes.map((recipe, index) => ( ))}

); }

export default App; get the correct id: fetch('API_URL_TO_ADD_RECIPE', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(recipeData), }) .then(response => response.json()) .then(data => console.log('New Recipe ID:', data.id)) .catch(error => console.error('Error:', error));

Or you may want follow this doc: https://blog.logrocket.com/modern-api-data-fetching-methods-react/

as for getting the id - after adding a recipe through an API call, the backend should return the new recipe's ID in response. Use this ID to navigate to the new recipe page