Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - How to re-fetch data after doing a filter in React.js with useContext

I got this component in React.js which make different kinds of filtering when I click a button, this is my code:

    import React, { useContext } from 'react';
    import { ModelsContext } from "../context/ModelsContext";
    
    const FilterNav = () => {

        const { modelos, guardarModelo } = useContext(ModelsContext);
        
        const filterSegment = e => {
    
            const segment = modelos.filter(modelo => modelo.segment === e.target.name);
            
            guardarModelo(segment);

        }

       
        return (
            <nav className="filter-container"> 
                <div className="container">
                    <h3 className="filter-element-title">Filtrar por</h3>
                    <button type="button" className="filter-element">Todos</button>
                    <button type="button" className="filter-element" name="Autos" onClick={filterSegment}>Autos</button>
                    <button type="button" className="filter-element" name="Pickups y Comerciales" onClick={filterSegment}>Pickups y Comerciales</button>
                    <button type="button" className="filter-element" name="SUVs y Crossovers" onClick={filterSegment}>SUVs y Crossovers</button>
                </div>
                <p className="filter-element-last">Ordenar por &#x5e;</p>
            </nav>
         );
    }
     
    export default FilterNav;

The information I get from the api with useContext in ModelsContext.jsx, here is what I wrote so far:

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

export const ModelsContext = createContext();

const ModelsProvider = (props) => {

        //State de modelos
        const [modelos, guardarModelo] = useState([]);

        const consultarAPI = async () => {
        const api = await fetch("https://challenge.agenciaego.tech/models");
        const modelos = await api.json();
        guardarModelo(modelos);
        }

        //Cargar un modelo
        useEffect(() => {
            consultarAPI()
        }, []);

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

export default ModelsProvider;

My issue is that when I filter the API modelos throught the filterSegment function I don't know how to re-fetch the data from the API, because when I do a new call to the filterSegment function it filters the filtered data. I've tried to add a boolean state, and I was thinking about adding another state with allthedata, but I really lost about implementing it, I'm still very new to React.js. I've search through stack overflow and google and I cannot get the answer, If you can give me a clue or some sort of guidance it will be appreciated.

Thanks so much!

question from:https://stackoverflow.com/questions/66056819/how-to-re-fetch-data-after-doing-a-filter-in-react-js-with-usecontext

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can add another state in the ModelsContext:

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

const consultarAPI = async () => {
    const api = await fetch("https://challenge.agenciaego.tech/models");
    const modelos = await api.json();
    guardarAllModelo(modelos);
    
    //uncomment if you want to have initial value for modelos state
    //guardarModelo(modelos);
}

// some codes ...

<ModelsContext.Provider
        value={{
            allModelos,
            modelos,
            guardarModelo
        }}
 >
        {props.children}
 </ModelsContext.Provider>

Then in the FilterNav component:

    const {allModelos, modelos, guardarModelo } = useContext(ModelsContext);
    
    const filterSegment = e => {

        const segment = allModelos.filter(modelo => modelo.segment === e.target.name);
        
        guardarModelo(segment);

    }

But this does not really re-fetch data from your web api. It just re-filters the first fetched data. if you want to re-fetch data from web api you can add consultarAPI in your context provider then call it somewhere.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...