-1

When I add the location.assign('AllBlog') it doesn't post the data but if I remove it, it works.

import React, { useState } from 'react'
import './PostBlog.css'
import axios from 'axios'

function PostBlog() {


    const [title , setTitle] =useState(null);
    const [body , setBody] =useState(null);
    const [PostDone , setPostDone] =useState(false);

    const handelPost =()=>{
        axios.post('http://127.0.0.1:7000/postBlog',{
            title:title,
            body:body
            })
            setPostDone(()=>true)
    }

    {PostDone ? window.location.assign('/AllBlog'): null}


return (
        <section className='Post-blog'>

            <h1 className='post-header-text'> Post what you Like</h1>

            <div className='form-post'>

            <label>
                <h3>title</h3>
                <input type="text" className='title-from' onChange={(e)=>     {setTitle(e.target.value)}}/>
            </label>
            <label>
                <h3>Pergraph</h3>
                <textarea type="text" className='p-from' rows="6" onChange={(e)=>{setBody(e.target.value)}}></textarea>
            </label>
            {/* <label>
                <h3>Upload Image</h3>
                <input type="file"/>
            </label> */}

            <button className='btn una' onClick={()=>handelPost()}>Post</button>
            </div>

        </section>
    )
}

export default PostBlog
halfer
  • 19,824
  • 17
  • 99
  • 186
Amar Ahmed
  • 13
  • 3

1 Answers1

0

Function axios.post is asynchronous. So window.location.assign might be executed before a finish of the request. To fix that make function handelPost asynchronous and add await to axios.post.

const handelPost = async () => {
  await axios.post('http://127.0.0.1:7000/postBlog', {
    title:title,
    body:body
  });

  setPostDone(() => true);
}
Daniil Emelin
  • 251
  • 1
  • 5