skip to Main Content

I have two pieces of code, the Front-end in React and the Bakc-end in Laravel, the problem is im calling the API to get an array of a SQL join but in the useEffect React Hook it doest get the info, but if i make a button to get it works, i don’t know why the useEffect Hook isn’t working properly

I partially solved the question by treating the response as an array but if you are sending more than 1 thing i still dont know what to do

I have this pieces of code

Laravel:

public function show($id)
    {
        $returned = response('El lote solicitado no existe', Response::HTTP_BAD_REQUEST);

        $lote = DB::table('lotes')
        ->leftjoin('articulos', 'lotes.idArticulo', '=', 'articulos.id')
        ->select('lotes.idLote', 'lotes.idArticulo', 'lotes.cantidad', 'lotes.consumoPreferente', 'lotes.observaciones', 'articulos.descripcion')
        ->where('lotes.id', $id)
        ->get();

        if($lote){
            $returned = response($lote, Response::HTTP_OK);
        }

        return $returned;
    }

React:

const [lote, setLote] = useState([])

    useEffect(() => {
        document.title = `Lote ${id}`
        getLote()
    }, [])

    const { id } = useParams()

    const getLote = async () => {
        try {
            const response = await axios.get(`${endpoint}/lote/${id}`)
            setLote(response.data)
        } catch (e) {
            console.log(`Error ${e}`)
        }

    }

The problem is that lote isn’t setting in the useEffect hook, but if i call the getLote function outside of it works.

Another issue is that if i change the laravel part to this works properly on the useEffect call:

I think the key is here, if i use the ‘findOrFail’ it works properly but if make a SQL query it doesn’t, but if im using the async – await it should wait, rigth?

$lote = Lote::findOrFail($id);
        if($lote ){
            $returned = response($lote , Response::HTTP_OK);
        }

        return $returned;

Also to mention im ussing axios to make the calls, could it be the problem too?

Do you know what could be happening?

2

Answers


  1. Chosen as BEST ANSWER

    I solved the question by doing an intermediate step

    If the data that is being sended is only one object in the array

    const [lote, setLote] = useState([])
    
        useEffect(() => {
            document.title = `Lote ${id}`
            getLote()
        }, [])
    
        const { id } = useParams()
    
        const getLote = async () => {
            try {
                const response = await axios.get(`${endpoint}/lote/${id}`)
                setLote(response.data[0])
            } catch (e) {
                console.log(`Error ${e}`)
            }
    
        }
    

    If the data that is being sended are more than one object in the array

    const [lote, setLote] = useState([])
    
        useEffect(() => {
            document.title = `Lote ${id}`
            getLote()
        }, [])
    
        const { id } = useParams()
    
        const getLote = async () => {
            try {
                const response = await axios.get(`${endpoint}/lote/${id}`)
                let newLote = response.data
                setLote(newLote)
            } catch (e) {
                console.log(`Error ${e}`)
            }
    
        }
    

    I don't know why this happens but this solution worked for me


  2. The first thing you need to do is to make sure that id is already defined in useEffect, so you need to re-write useEffect like this:

    useEffect(() => {
      if(!id) {
        return;
      }
      document.title = `Lote ${id}`
      getLote()
    }, [id]);
    

    also, I would recommend putting function in useCallback

    const getLote = useCallback(async () => {
            try {
                const response = await axios.get(`${endpoint}/lote/${id}`)
                setLote(response.data)
            } catch (e) {
                console.log(`Error ${e}`)
            }
    
        }, [id]);
    

    It is crucial to add relevant dependencies in deps array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search