Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

redux toolkit

> npm install @reduxjs/toolkit react-redux

# then follow along from here to install RTK to codebase
# https://redux-toolkit.js.org/tutorials/quick-start#create-a-redux-store
Comment

redux toolkit

If you are installing redux in an existing react project,
please be sure alter the index.js file to include the provider and
store from the redux module and app folder respectively. 
Comment

redux toolkit

yarn add @reduxjs/toolkit
// with template
yarn add @reduxjs/toolkit react-redux
Comment

redux toolkit

yarn add @reduxjs/toolkit react-redux
Comment

redux toolkit store

// store.js

import { configureStore } from '@reduxjs/toolkit'

export const store = configureStore({
  reducer: {},
})


// index.js 

import { store } from './app/store'
import { Provider } from 'react-redux'

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

Comment

redux js toolkit

// Redux + Plain JS template
npx create-react-app my-app --template redux

// Redux + TypeScript template
npx create-react-app my-app --template redux-typescript
Comment

reduxjs toolkit createaction

createAction('tagsLoadSuccess', (tags: string[]) => {
  return {
    payload: tags,
  };
})
Comment

implement REDUX to REACT using reduxjs/toolkit

// After new release of redux, we don't need to install/use too many packages,
// we just need below.

// necessary packages
> npm install @reduxjs/toolkit react-redux

// store.js:
import { configureStore } from '@reduxjs/toolkit';
import productsReducer from './StateSlice/productsSlice';

const store = configureStore({
  reducer: { products: productsReducer },
});

export default store;

// productsSlice.js:
import { createSlice } from '@reduxjs/toolkit';
import axios from 'axios';

const productsSlice = createSlice({
  name: 'products',
  initialState: {
    productLists: [],
    loading: true,
  },
  reducers: {
    PRODUCT_LIST_REQUEST: (products) => {
      products.loading = true;
    },
    PRODUCT_LIST_SUCCESS: (products, action) => {
      products.loading = false;
      products.productLists = action.payload;
    },
    PRODUCT_LIST_FAIL: (products, action) => {
      products.error = action.payload;
      products.loading = false;
    },
  },
});

// Action creators are generated for each case reducer function
export const { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL } =
  productsSlice.actions;

export default productsSlice.reducer;

// Action Creators
export const listProducts = () => async (dispatch) => {
  try {
    dispatch({
      type: PRODUCT_LIST_REQUEST.type,
    });

    const { data } = await axios.get('/api/products');

    dispatch({ type: PRODUCT_LIST_SUCCESS.type, payload: data });
  } catch (error) {
    dispatch({ type: PRODUCT_LIST_FAIL.type, payload: error.message });
  }
};

// Apply to react, HomeScreen.jsx:
import React, { useEffect } from 'react';

import { LoadingBox, MessageBox, Product } from '../components';

import { useDispatch, useSelector } from 'react-redux';
import { listProducts } from './../store/StateSlice/productsSlice';

const HomeScreen = () => {
  const dispatch = useDispatch();
  // productsSlice -> name is "products"
  // productsSlice -> initial "productLists, loading"
  const products = useSelector((state) => state.products);
  const { loading, error, productLists } = products;

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

  return (
    <div className="max-w-2xl mx-auto py-16 px-4 sm:py-24 sm:px-6 lg:max-w-7xl lg:px-8">
      {loading ? (
        <LoadingBox />
      ) : error ? (
        <MessageBox variant="danger">{error}</MessageBox>
      ) : (
        <>
          <h2 className="sr-only">Products</h2>
          <div className="grid grid-cols-1 gap-y-4 sm:grid-cols-2 sm:gap-x-6 sm:gap-y-10 lg:grid-cols-3 lg:gap-x-8">
            {productLists.map((product) => (
              <Product key={product.id} product={product} />
            ))}
          </div>
        </>
      )}
    </div>
  );
};

export default HomeScreen;

Comment

PREVIOUS NEXT
Code Example
Javascript :: JavaScript: Cycle through three-state checkbox states 
Javascript :: phaser add camera 
Javascript :: javascript how to random set rgb colors 
Javascript :: Javascript Area When All Sides are Known 
Javascript :: cannot setState in event handler 
Javascript :: javascript for website design center text 
Javascript :: sum of product of digits of a given number 
Javascript :: mdn javascript array 
Javascript :: registration page validation in react 
Javascript :: add array and sort 
Javascript :: general hardhat config js file code 
Javascript :: var logNums = function(num) {}; 
Javascript :: javascript goto or redirect to page 
Javascript :: livewire multiple root elements detected. this is not supported 
Javascript :: camelcase to css variable javascript 
Javascript :: The most obvious example is handling the click event, 
Javascript :: Backbone With Express 
Javascript :: how to properly make the navbar to be fixed to the top in react.jsx 
Javascript :: for-loop-how-to-loop-through-an-array-in-js 
Javascript :: remove duplicate node 
Javascript :: how to scroll element in javascript 
Javascript :: popper js 
Javascript :: invalid json response body 
Javascript :: jsx classname 
Javascript :: generate a link with javascript 
Javascript :: Node.js (node 11.12.0) sample 
Javascript :: rem api rest 
Javascript :: javascript Non-numeric String Results to NaN 
Javascript :: javascript Arrow Function as an Expressio 
Javascript :: JavaScript Generator Throw Method 
ADD CONTENT
Topic
Content
Source link
Name
1+8 =