Home > Software engineering >  Axios get request returns 404 when passed url path parameter
Axios get request returns 404 when passed url path parameter

Time:09-28

I have a React component "PostDetails" like this:

const PostDetails = () => {
const params = useParams();
const [post, setPost] = useState({});
const [fetchPostById, isLoading, error] = useFetching(async (id) => {
    const response = await PostService.getById(id);
    setPost(response.data);
})

useEffect(() => {
    fetchPostById(params.id)
}, [])

return (
    <div>
        <h1>Post details page for ID = {params.id}</h1>
        <div>{post.id}. {post.title}</div>
    </div>
);
};
export default PostDetails;

Custom hook "useFetching" is implemented like this:

export const useFetching = (callback) => {

const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');

const fetching = async () => {
    try {
        setIsLoading(true);
        await callback();
    } catch (e) {
        setError(e.message);
    } finally {
        setIsLoading(false);
    }
}

return [fetching, isLoading, error];
}

Utility class "PostService" is implemented like this:

export default class PostService {

static async getById(id) {
    const response = await axios.get("https://jsonplaceholder.typicode.com/posts/"   id);
    return response;
};
}

In browser console I get the error for "GET" request like this:

GET https://jsonplaceholder.typicode.com/posts/undefined 404

I tried to reformat my URL like this:

https://jsonplaceholder.typicode.com/posts/${id}

But still get the same error.

Why does "params.id" convert into undefined when I call my axios fetching request? What am I doing wrong here?

CodePudding user response:

Please try this

const PostDetails = () => {
const {id} = useParams();
const [post, setPost] = useState({});
const [fetchPostById, isLoading, error] = useFetching(async (id) => {
   const response = await PostService.getById(id);
   setPost(response.data);
 })

useEffect(() => {
   id && fetchPostById(id)
}, [id])

return (
    <div>
       <h1>Post details page for ID = {params.id}</h1>
       <div>{post.id}. {post.title}</div>
    </div>
);
};

CodePudding user response:

Add the params.id variable to the useEffect array dependencies:

useEffect(() => {
    fetchPostById(params.id)
}, [params.id])
  • Related