Search code examples
javascriptreactjsreact-hooksfetch-apireact-context

Problem in React.js with useContext data loading error 404


I have finished my project and uploaded it to Netlify. I got this trouble when I reload the page, I get an error 404. The console said that I got an undefined because the endpoint is not getting data, I guess. How could I solve or refactor my code in order to get riddle of this issue, Any recommendation?

Here is my useContext:

import React, { createContext, useState, useEffect } from 'react';

export const ModelsContext = createContext();

const ModelsProvider = (props) => {

        //State de modelos
        const [ modelo, guardarModelo ] = useState([]);
        const [ modelos, guardarModelos ] = useState([]);
        const [ allModelos, guardarAllModelo ] = useState([]);

        const { id } = modelo;

        console.log(id);

         //Cargar un modelo
         useEffect(() => {
             const consultarAPI = async () => {         
                try {
                    const api = await fetch("https://challenge.agenciaego.tech/models");
                    const modelos = await api.json();
    
                    const api2 = await fetch(`https://challenge.agenciaego.tech/models/${id ? id : ""}`);
                    const modelo = await api2.json();
           
                    guardarAllModelo(modelos);
                    guardarModelos(modelos);
                    guardarModelo(modelo);

                } catch (error) {
                   console.log(error); 
                }
             }
             consultarAPI()
         }, [id]);

    return (
        <ModelsContext.Provider
            value={{
                allModelos,
                modelo,
                modelos,
                guardarModelo,
                guardarModelos
            }}
        >
            {props.children}
        </ModelsContext.Provider>
    )
}

export default ModelsProvider;

Then is the link to the whole repository: https://github.com/patricio1984/desafio-ego

And finally the deploy link: https://musing-hermann-5129b4.netlify.app/models


Solution

  • This is an issue with Netlify, not your app. You need to tell Netlify to return your index.html for all paths.

    https://docs.netlify.com/routing/redirects/

    Create a new file in the root of your project called netlify.toml and add the following

    netlify.toml

    [[redirects]]
      from = "/*"
      to = "/index.html"
      status = 200