Привет, ребята, сегодня я собираюсь показать вам, как использовать combReducers в Redux. помог мне реализовать логику, которую я пытался найти

Я предполагаю, что вы уже знаете о редукции, поэтому я собираюсь показать combReducer напрямую, не рассказывая обо всем процессе настройки редукции.

Давайте начнем…

Редукторы -

КонтактыReducer.js

import axios from 'axios'

const contactReducer = (state = [], action) => {
    switch (action.type) {
        case "FETCH":
            state = action.payload
            return state
        case "ADD_CONTACT":
            axios
                .post("http://localhost:3001/Register", action.payload)
                .then((res) => console.log(res))
                .catch((err) => console.log(err));
            return state
        case "UPDATE_CONTACT":
            axios
                .put("http://localhost:3001/update", action.payload)
                .then((response) => console.log(response))
                .catch((err) => console.log(err));
            return state
        case "DELETE_CONTACT":
            console.log(action.payload)
            axios             
         .delete(`http://localhost:3001/delete/${action.payload}`)
                .then((response) => console.log(response))
                .catch((err) => console.log(err));
            return state
        default:
            return state;
    }
}

export default contactReducer;

SignupReducers.js

import axios from 'axios'

const contactReducer = (state = [], action) => {
    switch (action.type) {
        case "FETCH_USER":
            state = action.payload
            return state
        case "ADD_USER":
            axios
                .post("http://localhost:3001/RegisterUser", action.payload)
                .then((res) => console.log(res))
                .catch((err) => console.log(err));
            return state
        default:
            return state;
    }
}

export default contactReducer;

Я создал 2 отдельных редюсера, и каждый редуктор выполняет действие в разных базах данных и возвращает ответ отдельно

Редукторы.js

import { combineReducers } from "redux";
import contactReducer from "./contactReducer";
import signupReducer from "./signupReducer";

const rootReducer = combineReducers({ contact: contactReducer, signup: signupReducer })

export default rootReducer

Как видите, я создал rootReducer, который содержит оба редуктора, а именно контакт и регистрацию, и эти идентификаторы будут использоваться для доступа к редукторам из состояния (например, state.contact).

# Использование редукторов отдельно

index.js — Здесь мы создаем хранилище для редукса.

import { createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from './redux/Reducers';
import { Provider } from 'react-redux';

const store = createStore(rootReducer, composeWithDevTools());

Как видите, мы создали хранилище, используя наш rootReducer, который имеет оба состояния редюсеров.

# Доступ к состояниям каждого редюсера

AddContact.js

import { useSelector, useDispatch } from 'react-redux'

const AddContact = () => {
const contacts = useSelector(state => state.contact);
//getting the data from initial state of contact
const dispatch = useDispatch();//for dispatching the method
.
.
.
.
  const data = {
    uniqueId,
    name,
    email,
    number
}
dispatch({ type: "ADD_CONTACT", payload: data });
//this will perform the operation in contact reducers
.
.
.
}

Signup.js

import { useSelector, useDispatch } from 'react-redux'

const Signup = () => {
.
.
const dispatch = useDispatch();

useEffect(() => {
        axios.get("http://localhost:3001/SignupInfo")
            .then((response) => {
//this will perform the operation on signup reducer
                dispatch({ type: "FETCH_USER", payload: response.data })
            })
            .catch((err) => console.log(err));
    }, [dispatch])
    const users = useSelector((state) => state.signup);
//getting the data from initial state of signup
}

Вот и все для этого поста.
СПАСИБО, ЧТО ПРОЧИТАЛИ ЭТО ПОСТ, И ЕСЛИ ВЫ ОБНАРУЖИТЕ ЛЮБУЮ ОШИБКУ ИЛИ ХОТИТЕ СДЕЛАТЬ ЛЮБОЕ ПРЕДЛОЖЕНИЕ, ПОЖАЛУЙСТА, ОТМЕТЬТЕ ОБ ЭТОМ В РАЗДЕЛЕ КОММЕНТАРИЙ.
^^Вы можете помочь мне некоторым пожертвованием по ссылке ниже Спасибо👇👇 ^^
☕ → https://www.buymeacoffee.com/waaduheck

Также проверьте эти сообщения
https://dev.to/shubhamtiwari909/css-claymorphism-2pkd

https://dev.to/shubhamtiwari909/styled-componenets-react-js-15kk

https://dev.to/shubhamtiwari909/introduction-to-tailwind-best-css-framework-1gdj