0
import React from 'react'
import Products from '../components/Products'
import { setCategory } from '../app/productSlice';
import { useDispatch, } from 'react-redux'

const Home = () => {
  const dispatch = useDispatch();

  const handleFilter = (category) => {
    dispatch(setCategory(category))
  }
  return (
    <div className='max-w-[1240px] py-8 mx-auto px-4'>

      <div className='flex flex-wrap'>
        <button className='my-1 mr-1 border-black text-black-600 hover:bg-black hover:text-white border rounded-xl px-5 py-1'>All</button>
        <button onClick={() => handleFilter('jewelery')} className='m-1 border-black text-black-600 hover:bg-black hover:text-white border rounded-xl px-5 py-1'>Mens</button>
        <button className='m-1 border-black text-black-600 hover:bg-black hover:text-white border rounded-xl px-5 py-1'>Womens</button>
        <button className='m-1 border-black text-black-600 hover:bg-black hover:text-white border rounded-xl px-5 py-1'>Electronics</button>
        <button className='m-1 border-black text-black-600 hover:bg-black hover:text-white border rounded-xl px-5 py-1'>Jewelery</button>
      </div>

      <section className='py-4'>
        <Products />
      </section>
    </div>
  )
}

export default Home
import { createSlice } from '@reduxjs/toolkit'

export const STATUSES = Object.freeze({
    IDLE: 'idle',
    ERROR: "error",
    LOADING: "loading"
})

const productSlice = createSlice({
    name: 'product',
    initialState: {
        data: [],
        status: STATUSES.IDLE
    },
    reducers: {
        setProducts(state, action) {
            state.data = action.payload
        },
        setStatus(state, action) {
            state.status = action.payload
        },
        setCategory(state, action) {
            return state.data.filter((item) => item.category === action.payload)
        },
    }
})

export const { setProducts, setStatus, setCategory } = productSlice.actions
export default productSlice.reducer

export function fetchProducts() {
    return async function fetchProductThunk(dispatch, getstate) {
        dispatch(setStatus(STATUSES.LOADING))
        try {
            const res = await fetch('https://fakestoreapi.com/products/')
            const data = await res.json();
            dispatch(setProducts(data))
            dispatch(setStatus(STATUSES.IDLE))
        } catch (err) {
            console.log(err)
            dispatch(setStatus(STATUSES.ERROR))
        }
    }
}

In this code i am fetching data with redux-thunk and now I want when someone click on button than the previous fetched product details in which is stored in data state will change according to category i am sending from home.js

so can anyone explain how to update the store data according to category i am dispatching.

here is image of website

Sujjeee
  • 15
  • 4

0 Answers0