Snippets Collections
import { fetchBaseQuery } from '@reduxjs/toolkit/query'
import { tokenReceived, loggedOut } from './authSlice'

const baseQuery = fetchBaseQuery({ baseUrl: '/' })
const baseQueryWithReauth = async (args, api, extraOptions) => {
  let result = await baseQuery(args, api, extraOptions)
  if (result.error && result.error.status === 401) {
    // try to get a new token
    const refreshResult = await baseQuery('/refreshToken', api, extraOptions)
    if (refreshResult.data) {
      // store the new token
      api.dispatch(tokenReceived(refreshResult.data))
      // retry the initial query
      result = await baseQuery(args, api, extraOptions)
    } else {
      api.dispatch(loggedOut())
    }
  }
  return result
}
import { createAsyncThunk } from "@reduxjs/toolkit";
import { APIname } from "APIname-file-path";

export const actionName = createAsyncThunk(
  "sliceName/actionName",
  async (params, thunkAPI) => {
    const { dispatch, getState, rejectWithValue} = thunkAPI  // more information on redux document
    const { data } = params // action parameters when it is called 
    
    let response;

    try {
      response = await APIname();

      return { response };
    } catch (err) {
      switch (err?.response?.status) {
        case 400:
          return Promise.reject(err?.response?.data);
        case 500:
          return Promise.reject(new Error("سرور با مشکل مواجه شده است"));
        default:
          return Promise.reject(new Error("اینترنت خود  را چک کنید"));
      }
    }
    return rejectWithValue(err.response.data);
  }
);
import React, { useState, useEffect } from 'react';
 
export default function PageTitle() {
  const [name, setName] = useState('');
 
 useEffect(() => {
    document.title = `Hi, ${name}`;
  }, [name]);
 
  return (
    <div>
      <p>Use {name} input field below to rename this page!</p>
      <input 
        onChange={({target}) => setName(target.value)} 
        value={name} 
        type='text' />
    </div>
  );
}

// now the entrry of great functional componentsw useEffect
const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};

const mapStateToProps = (state) => {
  return {
    messages: state
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    submitNewMessage: (message) => {
      dispatch(addMessage(message));
    }
  }
};

class Presentational extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h3>This is a Presentational Component</h3>
  }
};

const connect = ReactRedux.connect;
// change code below this line

const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps) (Presentational)
const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};

const mapStateToProps = (state) => {
  return {
    messages: state
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    submitNewMessage: (message) => {
      dispatch(addMessage(message));
    }
  }
};

class Presentational extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h3>This is a Presentational Component</h3>
  }
};

const connect = ReactRedux.connect;
// change code below this line

const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps) (Presentational)
const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};

const mapStateToProps = (state) => {
  return {
    messages: state
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    submitNewMessage: (message) => {
      dispatch(addMessage(message));
    }
  }
};

class Presentational extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h3>This is a Presentational Component</h3>
  }
};

const connect = ReactRedux.connect;
// change code below this line

const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps) (Presentational)
import { useSelector, TypedUseSelectorHook } from "react-redux";
// Import type of state 
// Import {RootState} from '../store'

export const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector;
const [ user, setUser ] = useState(JSON.parse(localStorage.getItem('profile'))); //convert to object

const logout = () =>{
        dispatch({type: 'LOGOUT'});
        history.push("/");
        setUser(null);
    }

    useEffect(()=>{
        const token = user?.token;

        //JWT check if token expired
        if(token){
            const decodedToken = decode(token)
            if(decodedToken.exp*1000 < newDate().getTime()) logout();
        }
        setUser(JSON.parse(localStorage.getItem('profile')))
    },[location])
star

Sat Jun 24 2023 15:46:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/72613859/refresh-token-with-redux-toolkit-query

#javascript #redux #rtk
star

Mon Apr 25 2022 11:42:41 GMT+0000 (Coordinated Universal Time) https://redux-toolkit.js.org/api/createAsyncThunk

#redux
star

Sun Feb 20 2022 17:29:16 GMT+0000 (Coordinated Universal Time) https://egghead.io/q/redux?access_state

#redux
star

Sun Feb 20 2022 17:16:47 GMT+0000 (Coordinated Universal Time) https://egghead.io/q/react?access_state

#react #redux
star

Sat Feb 19 2022 18:07:27 GMT+0000 (Coordinated Universal Time)

#redux #react
star

Sat Feb 19 2022 17:57:24 GMT+0000 (Coordinated Universal Time)

#redux #react
star

Sat Feb 19 2022 17:57:20 GMT+0000 (Coordinated Universal Time)

#redux #react
star

Sat Feb 19 2022 17:55:50 GMT+0000 (Coordinated Universal Time)

#redux #react
star

Sat Feb 19 2022 17:40:37 GMT+0000 (Coordinated Universal Time) https://www.pluralsight.com/guides/code-splitting-your-redux-application

#redux #react
star

Sat Feb 19 2022 17:39:40 GMT+0000 (Coordinated Universal Time) https://www.pluralsight.com/guides/code-splitting-your-redux-application

#redux #react
star

Tue Jul 20 2021 06:31:09 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=LKlO8vLvUao&list=PL6QREj8te1P7VSwhrMf3D3Xt4V6_SRkhu&index=3

#react.js #redux

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension