bassam malla
bassam malla

Reputation: 99

react repeat request multiple time

I am building a React component but when rendering the component, the request done two times even if the first request success

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router';
import Post from './Post';

export const SinglePost = () => {

   const { id } = useParams();
   const getData =  async() => {
       await axios.get(`post/${id}`)
       .then((response)=>{
          return response.data
       })
       .catch((err)=>{
          return err
       })
   }
  return <Post post = {getData()} />
}

Is there a common way to fix it? Thanks.

Here my index.tsx

const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement);

root.render(
 <Provider store ={store}>
    <App />
 </Provider>
);

The error happens I think when passing the result to Post component. Even in that component, the request to that URL is never made.

Edit

I am rendering the component inside app.tsx by this code

<Route path="post/:id" element={<SinglePost/>}/>

Edit2

Post object contains:

Object { id: 132, content: "", updated: "2022-10-08T09:56:37.070618Z", image: "http://127.0.0.1:8000/media/images/admin%40socialbook.org/posts/b2e5d26fff1965a4.jpeg", created: "2022-10-08T09:56:37.070618Z", author: {…} }

Upvotes: 2

Views: 385

Answers (3)

omar
omar

Reputation: 268

The main reason why it throws an error, is because the component did not mount to call useEffect, so I think giving initial value to the state that holds post will work, for example:

var initialValue = {
    info:"",
    author:"",
    content:""
}

outside the component then define const [singlePost, setSinglePost] = useState(initialValue)

Inside your component finally when you get a response set that response to setSinglePost

Upvotes: 1

MohamedZh
MohamedZh

Reputation: 466

This is due to React Strict mode, and it only happens in development. It's enabled by default for your whole React app. If you wish to remove it, go to your index.js and remove the tags <React.StrictMode> wrapping your app.

Upvotes: 0

ctkr
ctkr

Reputation: 66

It may have something to do with React.StrictMode. If you remove this, it should only render once.

I believe that this only happens in development. In production this wouldn't happen, but I may be wrong.

Upvotes: 0

Related Questions