Next.js Discord

Discord Forum

infer types from axios

Unanswered
Maltese posted this in #help-forum
Open in Discord
MalteseOP
Hello, guys! I have the following problem. There is a posts/route GET that returns either
NextResponse.json(
      {
        posts,
        totalPosts,
      },
      { status: 200 }
    );


or
 NextResponse.json(
      { error: 'Failed to retrieve posts' },
      { status: 500 }
    );


How to handle it correctly on client. If I recive {error} from const response = await axios.get<GetPostsResponse>() and its in try catch block, it will automaticly go to catch, but ts doesn't know this, he thinks that I can get {error} and continue the code in the try block, but this can't happen because axios will throw error. So the question is, what is the best practice here to get the correct types


function isSuccessResponse(
  data: GetPostsResponse
): data is Exclude<GetPostsResponse, { error: string }> {
  return (data as { posts?: unknown }).posts !== undefined;
}

 useEffect(() => {
    const fetchPosts = async () => {
      setLoading(true);
      const postPerPage = 2;
      const skip = (currentPage - 1) * postPerPage;

      try {
        const response = await axios.get<GetPostsResponse>(
          `/api/posts?skip=${skip}&take=${postPerPage}`
        );
        const data = response.data;

        if (isSuccessResponse(data)) {
          setPosts(data.posts);
          setTotalPages(Math.ceil(data.totalPosts / postPerPage));
        }
      } catch (error) {
        if (axios.isAxiosError<{ error: string }>(error)) {
          console.log(error.response?.data.error || 'Something went wrong');
        } else if (error instanceof Error) {
          console.log(error.message);
        } else {
          console.log(JSON.stringify(error));
        }
      } finally {
        setLoading(false);
      }
    };

    fetchPosts();
  }, [currentPage]);


route.ts
export type GetPostsResponse = Awaited<ReturnType<typeof GET>> extends NextResponse<infer T> ? T : never;

0 Replies