Skip to content

Instantly share code, notes, and snippets.

@nurmdrafi
Last active November 16, 2022 19:17
Show Gist options
  • Save nurmdrafi/cdcda75ab9646ecbc12626665f55969c to your computer and use it in GitHub Desktop.
Save nurmdrafi/cdcda75ab9646ecbc12626665f55969c to your computer and use it in GitHub Desktop.

store.js

import { configureStore } from "@reduxjs/toolkit";
import postsReducer from "./reducers/postsReducer";

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

postsReducers.js

import { createSlice } from "@reduxjs/toolkit";
import { getPosts } from "../actions/postActions";

const BASE_URL = "https://jsonplaceholder.typicode.com/posts";

const initialState = {
  posts: [],
};

// export const deletePost = createAsyncThunk(
//   "post/deletePost",
//   async (initialPost) => {
//     const { id } = initialPost;
//     try {
//       const response = await axios.delete(`${BASE_URL}/${id}`);
//       if (response?.status === 200) return initialPost;
//       return `${response.status} : ${response.statusText}`;
//     } catch (error) {
//       return error.message;
//     }
//   }
// );

const postsSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getPosts.fulfilled, (state, action) => {
      state.posts.push(action.payload);
    });
  },
});

export const { setPosts } = postsSlice.actions;
export default postsSlice.reducer;

postActions.js

import { createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const BASE_URL = "https://jsonplaceholder.typicode.com/posts";

// GET POST
export const getPosts = createAsyncThunk("posts/getPosts", async () => {
  try {
    const res = await axios.get(BASE_URL);
    return res.data;
  } catch (error) {
    console.error(error);
  }
});

CustomTable.js

import { Button } from "antd";
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";

// Import Actions & Methods
import { getPosts } from "../redux/actions/postActions";

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

  const posts = useSelector((state) => state?.posts?.posts ?? []);

  useEffect(() => {
    // Get user list
    dispatch(getPosts());
  }, []);

  // dispatch(getPosts());
  console.log(posts);

  return (
    <div>
      <Button onClick={() => dispatch(getPosts())}>Load Post</Button>
    </div>
  );
};

export default CustomTable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment