Post request using Redux-Thunk Middleware In Redux-Toolkit
Today we’ll learn how to make a post request using redux-thunk middleware in redux-toolkit.
You can read this article on Medium
Before we begin, you must know read this article on how to make get request using Redux-Thunk Middleware In Redux-Toolkit.
Because I have deeply explained in my previous article how to make get request using Redux-Thunk Middleware In Redux-Toolkit?. so now I will quickly jump to the topic
So far, we have made the get request and displayed the data on the browser.
Let’s now make a post request to the JSONPlaceholder — Free Fake REST API
Let’s create a function inside the postSlice.js
// make post request to server and console the response
export const sendPost = createAsyncThunk('posts/sendPosts',async(obj)=>{
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify(obj),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
})
First, we have to define the action creator, i.e.?posts/sendPosts,?and we’ll pass the argument to our async function that is an object that’s sent to the server.
After making the request we simply console our response.
let’s call this function inside the component.
import {fetchPosts, sendPost, getPost, getLoading} from '../redux/postSlice';
After that let’s add the two input fields and also added the submit button. one for the title and one for the body.
<div className="top">
<label htmlFor="title">
Title:
<input
type="text"
name='title'
value={titleValue}
onChange={(e)=>setTitleValue(e.target.value)} />
</label>
<label htmlFor="body">
Body:
<input
type="text"
name='body'
value={value}
onChange={(e)=>setValue(e.target.value)} />
</label>
<button
onClick= {()=>dispatch(sendPost({title:titleValue,body:value,userId:'1'}))}>submit</button>
</div>
Here we’re using useState to handle our state.
领英推荐
Let’s define the useState hook.
const [value,setValue] = useState('')
const [titleValue,setTitleValue] = useState('');;
Here we’re dispatching our sendPost function and we are passing an object as a parameter that have title value and body value and userId that is constant
<button
onClick={()=>dispatch(sendPost({title:titleValue,body:value,userId:'1'}))}>submit
</button>
If now you click on your button you will see the response in you console.
here is the full code
PostSlice.js
import { createSlice,createAsyncThunk } from "@reduxjs/toolkit";
const GET_POST_URL= "https://jsonplaceholder.typicode.com/posts";
const initialState = {
post:[],
error:'',
loading:false
}
// fetch the post
export const fetchPosts = createAsyncThunk(
'posts/fetchPosts',
async () => {
const response = await fetch(GET_POST_URL)
const data = await response.json();
return data
}
)
// make post request to server and console the response
export const sendPost = createAsyncThunk('posts/sendPosts',async(obj)=>{
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify(obj),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
})
const postSlice = createSlice({
name: 'posts',
initialState,
reducers:{},
extraReducers:(builder)=>{
builder
.addCase(fetchPosts.pending,(state)=>{
state.loading=true
})
.addCase(fetchPosts.fulfilled,(state,action)=>{
state.loading=false
state.post=action.payload
})
.addCase(fetchPosts.rejected,(state,action)=>{
state.loading=false
state.error=action.error.message
})
}
});
export default postSlice.reducer;
export const getPost = (state) => state.postReducer.post;
export const getLoading = (state) => state.postReducer.loading;
PostList.jsx
import React, { useState,useEffect } from 'react'
import {fetchPosts,sendPost,getPost,getLoading} from '../redux/postSlice';
import {useSelector,useDispatch} from 'react-redux'
const PostList = () => {
const [value,setValue] = useState('');
const [titleValue,setTitleValue] = useState('');
const getPosts = useSelector(getPost);
const dispatch = useDispatch()
useEffect(()=>{
dispatch(fetchPosts());
},[]);
return (
<>
<div className="top">
<label htmlFor="title">
Title:
<input
type="text"
name='title'
value={titleValue}
onChange={(e)=>setTitleValue(e.target.value)} />
</label>
<label htmlFor="body">
Body:
<input
type="text"
name='body'
value={value}
onChange={(e)=>setValue(e.target.value)} />
</label>
<button
onClick={()=>dispatch(sendPost({title:titleValue,body:value,userId:'1'}))}>submit
</button>
</div>
<div className='post-wrapper'>
{
getPosts.map((post,index)=>(
<div className='single-post' key={index}>
<h4>{post.title}</h4>
<h6>{post.body}</h6>
</div>
))
}
</div>
</>
)
}
export default PostList;
Hope you like it ??
Happy coding!
want to give suggestions:-
have a look at?my portfolio
Email me at [email protected]