Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import axios from "axios";
export default {
getUsers: async () => {
return await axios.get(
"https://5f426adcd4b4790016fd79c8.mockapi.io/api/v1/users"
);
},
};
import { configureStore, ThunkAction, Action } from "@reduxjs/toolkit";
import usersReducer from "../features/users/usersSlice";
export const store = configureStore({
reducer: {
users: usersReducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>;
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { fetchUsers } from "./usersSlice";
import { RootState } from "../../app/store";
export default function () {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchUsers());
}, [dispatch]);
const users = useSelector((state: RootState) => {
return state.users;
});
return (
<>
{users?.users?.map((user) => {
return <div key={user.id}>{user.name}</div>;
})}
</>
);
}
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import api from "./api";
import { DefaultRootState } from "react-redux";
interface User {
id: number;
createdAt: Date;
name: string;
avatar: string;
}
export interface UsersState extends DefaultRootState {
users: User[];
}
const initialState: UsersState = {
users: [],
};
export const fetchUsers = createAsyncThunk("users/get", async () => {
const response = await api.getUsers();
return response.data;
});
export const usersSlice = createSlice({
name: "users",
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchUsers.fulfilled, (state, action) => {
const payload: User[] = action.payload;
state.users.push(...payload);
});
},
});
export default usersSlice.reducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.