Keneth Smith
Keneth Smith

Reputation: 13

React state overwrites the current reducer

I have a component called Restaurante where I'm trying to call the action FETCH_ALL from my restaurante reducer. I'm consuming that information successfully from MongoDB.

To get that information I'm using the useEffect hook where I call the action getRestaurantes()

useEffect(() => {
   dispatch(getRestaurantes());
}, [ currentId, dispatch ]);

I have another component called RestauranteData which is a table that displays all the information obtained using dispatch and the useSelector hook

const dispatch = useDispatch();
const restaurantes = useSelector((state) => state.restaurantes);

As you can see the information is displaying successfully in the table:

restaurants table

I need to call another action to get the information from another collection called consecutitvos. This collection has information that would allow me to create a custom id when the user creates a new restaurant. To get that information I have an action called getConsecutivos.

useEffect(() => {
        dispatch(getConsecutivos());
    });

const selectedConsecutivo = useSelector((state) => !currentConsecutivo ? state.consecutivos.find((c) => c.type === "Restaurants") : null);

The issue that I'm having is that when I call that action the state overwrites and sometimes the table displayed the consecutitvos information instead of the restaurants' information. If I reload the page the information displayed in the table changes.

This is the complete code I have in my Restaurante component

const Restaurante = () => {

    const [currentId, setCurrenteId] = useState(null);
    const [show, setShow] = useState(false);
    const dispatch = useDispatch();
    const [inputSearchTerm, setinputSearchTerm] = useState('');
    const [selectedTypeSearch, setSelectedTypeSearch] = useState('');
    const [inputSearchTermError, setinputSearchTermError] = useState('');
    const [currentConsecutivo, setCurrentConsecutivo] = useState(null);

    const reload=()=>{window.location.reload()};
   
    useEffect(() => {
        dispatch(getConsecutivos());
    });

   const selectedConsecutivo = useSelector((state) => !currentConsecutivo ? state.consecutivos.find((c) => c.tipo === "Restaurantes") : null);
   console.table(selectedConsecutivo);

    

    
    
    useEffect(() => {
        dispatch(getRestaurantes());
    }, [ currentId, dispatch ]);

RestauranteData complete code (Rendering the table)

const RestauranteData = ({ setShow, currentId,  setCurrenteId, inputSearchTerm, selectedTypeSearch}) => {

    
    const dispatch = useDispatch();
    const restaurantes = useSelector((state) => state.restaurantes);

    console.log(restaurantes);

    return(
    
        <Table className="text-center" striped>
            <thead>
                <tr>
                    <th>Código</th>
                    <th>Nombre</th>
                    <th>Dirección</th>
                    <th>Cantidad de Clientes</th>
                    <th>Teléfono</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tbody className="text-white">
                {restaurantes.filter( restaurante => {

                    if(!inputSearchTerm){
                        return restaurante;

                    }else if( selectedTypeSearch === "codigo"){

                        if(restaurante.codigo.toLowerCase().includes(inputSearchTerm.toLowerCase())){

                            console.table(restaurante);
                            return restaurante;
                        }
                    }else if( selectedTypeSearch === "nombre"){

                        console.log(restaurante.descripcion);

                        if(restaurante.nombre.toLowerCase().includes(inputSearchTerm.toLowerCase())){
                            return restaurante;
                        }
                    }
                }).map( restaurante => {
        
                    return(
                        <tr key={restaurante._id}>
                            <td key={restaurante.codigo}>{restaurante.codigo}</td>
                            <td key={restaurante.nombre}>{restaurante.nombre}</td>
                            <td key={restaurante.direccion}>{restaurante.direccion}</td>
                            <td key="2">2</td>
                            <td key={restaurante.telefono}>{restaurante.telefono}</td>
                            <td>
                                <Button variant="outline-light" className="btn-action" onClick={() => {setCurrenteId(restaurante._id); setShow(true)}} ><FontAwesomeIcon icon={faPen}></FontAwesomeIcon></Button>
                                <Button variant="outline-light" className="btn-action" onClick={() => dispatch(deleteRestaurante(restaurante._id))}><FontAwesomeIcon icon={faTrash}></FontAwesomeIcon></Button>
                            </td>
                        </tr>
                    )
                })}
            </tbody>
        </Table>
        
    );
}

export default RestauranteData; 

restaurantes.js reducer code

const reducer = (restaurantes = [], action) => {
    switch (action.type) {
        case 'DELETE':
            return restaurantes.filter((restaurante) => restaurante._id !== action.payload); //keep all the restaurantes but the action.payload
        case 'UPDATE':
            return restaurantes.map((restaurante) => restaurante._id === action.payload.id ? action.payload : restaurante);
        case 'FETCH_ALL':
            return action.payload;
        case 'CREATE':
            return [...restaurantes, action.payload];
    
        default:
            return restaurantes;
    }
}

export default reducer; 

consecutivos.js reducers code

const reducer = (consecutivos = [], action) => {
    switch (action.type) {
        case 'DELETE':
            return consecutivos.filter((consecutivo) => consecutivo._id !== action.payload); //keep all the consecutivos but the action.payload
        case 'UPDATE':
            return consecutivos.map((consecutivo) => consecutivo._id === action.payload.id ? action.payload : consecutivo);
        case 'FETCH_ALL':
            return action.payload;
        case 'CREATE':
            return [...consecutivos, action.payload];
    
        default:
            return consecutivos;
    }
}

export default reducer; 

index.js combined reducers

import { combineReducers } from 'redux';
import consecutivos from './consecutivos';
import restaurantes from './restaurantes';


export default combineReducers({ consecutivos, restaurantes });

index.js of the application

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'; //Keep track of the Store
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';

import App from './App';

const store = createStore(reducers, compose(applyMiddleware(thunk)));


ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, 
    document.getElementById('root')
);

Upvotes: 0

Views: 58

Answers (1)

Baskaran Ajiharan
Baskaran Ajiharan

Reputation: 508

In your reducer function, u will use different action type names instead of using the same names & change action type names in your action methods also

const reducer = (restaurantes = [], action) => {
    switch (action.type) {
        case 'DELETE_RESTAURANT':
            return restaurantes.filter((restaurante) => restaurante._id !== action.payload); //keep all the restaurantes but the action.payload
        case 'UPDATE_RESTAURANT':
            return restaurantes.map((restaurante) => restaurante._id === action.payload.id ? action.payload : restaurante);
        case 'FETCH_ALL_RESTAURANT':
            return action.payload;
        case 'CREATE_RESTAURANT':
            return [...restaurantes, action.payload];
    
        default:
            return restaurantes;
    }
}

export default reducer; 



const reducer = (consecutivos = [], action) => {
    switch (action.type) {
        case 'DELETE_CONSECUTIVOS':
            return consecutivos.filter((consecutivo) => consecutivo._id !== action.payload); //keep all the consecutivos but the action.payload
        case 'UPDATE_CONSECUTIVOS':
            return consecutivos.map((consecutivo) => consecutivo._id === action.payload.id ? action.payload : consecutivo);
        case 'FETCH_ALL_CONSECUTIVOS':
            return action.payload;
        case 'CREATE_CONSECUTIVOS':
            return [...consecutivos, action.payload];
    
        default:
            return consecutivos;
    }
}

export default reducer; 

Upvotes: 1

Related Questions