While running below code, I am facing “Error: 404 Async is in anonymous await”. There are two files provided app.js and second file is api.jsx. I am using RTK query and doing CRUD operation. While performing it I am sending data in posts and passing it to Adddata component after button click. But at the same time facing error 404.
import "./App.css";
import { useGetApiByNameQuery, useCreatePostMutation } from "./services/api";
function App() {
const { data, error, isLoading, isSuccess, isFetching } =
useGetApiByNameQuery();
console.log(data);
return (
<div className="App">
<h1>React RTK Query practice</h1>
{isLoading && <h2>Loading...</h2>}
{isFetching && <h2>Fetching....</h2>}
{error && <h2>error....</h2>}
{isSuccess && (
<div>
{Object.keys(data).map((item) => {
return (
<div key={data[item._id]}>
<span>
{" "}
{item} : {data[item]}
</span>
</div>
);
})}
</div>
)}
<div>
<Adddata />
</div>
</div>
);
}
export const Adddata = () => {
const [adddata] = useCreatePostMutation();
const posts = {
id: "2",
title: "posted",
author: "dikshant",
};
var handleData;
handleData = async () => {
await adddata(posts);
};
return <button onClick={handleData}>Add Data</button>;
};
export default App;
api.jsx code –
// Need to use the React-specific entry point to import createApi
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const api = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({
baseUrl: "http://localhost:3000/",
}),
endpoints: (builder) => ({
getApiByName: builder.query({
query: () => "/0",
}),
createPost: builder.mutation({
query: (newpost) => ({
url: "/0",
method: "POST",
body: newpost,
}),
}),
}),
});
export const { useGetApiByNameQuery, useCreatePostMutation } = api;