I am getting post data from database through RTK useQuery, but when i upload new post through useMutation, it dosn't update data on Screen first time. After load the page it shows data. How to do this to get data without load a page.
// this is get post RTK query function
`const getallPosts = useGetallPostsQuery();
const postData = async () => {
if(getallPosts.currentData){
getallPosts.currentData.data.posts.map(item => dispatch(setPost(item)))
console.log(getallPosts.currentData.data)
}
};`
this is my Api file
`createPost:builder.mutation({
query: (data) => {
return {
url: "create_post",
method: "POST",
body: data,
headers: {
"Content-type": "application/json",
},
};
},
}),
getallPosts: builder.query({
query: () => ({
url: 'get_all_posts',
method: 'GET',
headers : {
"Content-type": "application/json",
}
}),
providesTags : ['Posts']
}),`
i tried tags caching but it didn't worked
Related
i need to post and get my data when clicking on the same button [like write and show comment] , but when i click the button everything is going well but a request with 304 status code is running with infinite loop, can someone help ?
const addCommentHandler = (commentData) => {
axios({
url: `/api/comment/${eventId}`,
method: "post",
data: commentData,
headers: {
"Content-type": "application/json",
},
}).then((res) => {
const data = res.data;
console.log(data);
});
axios({
url: `/api/comment/${eventId}`,
method: "get",
}).then((res) => {
const data = res.data;
setComments(data.comments);
});
};
useEffect(() => {
addCommentHandler();
}, []);
It seems like You want to Post the Data and then want to get the Updated Comments.But you are creating Two Asynchronous Api Calls..
304 Status Code Means " The requested resource has not been modified since the last time you accessed it "
Please Refresh Cache and try Again..
const addCommentHandler = async (commentData) => {
// add Try Catch for Errors..
const responseData = await axios({
url: `/api/comment/${eventId}`,
method: "post",
data: commentData,
headers: {
"Content-type": "application/json",
},
})
const resData = await axios({
url: `/api/comment/${eventId}`,
method: "get",
})
setComments(resData.data.comments);
};
useEffect(() => {
// Pass CommentData as Params in addCommentHandler
addCommentHandler();
}, []);`
I have an application that stores to its state files' content, whether images, audio or both, as shown here with the mediaAudio object key:
In my react.js code, I make my post as such:
var bodyFormData = new FormData();
bodyFormData.append('data', formData);
axios({
method: "post",
url: 'http://localhost:5000/post-entry',
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then((response) => {
console.log(response);
})
.catch((response) => {
console.log(response);
});
In my node.js code, I retrieve my data as such:
app.post('/post-entry', (req, res) => {
let data = req.body.data;
console.log(data);
});
However, I'm not able to get the data being logged, it returns undefined.
What is happening?
Thanks
I am trying to hit API with axios but response.data variable is empty. While using axios.create but when i directly hit API with axios.post. It works fine. I want to get the response through axios.create. Here is my axios create code
const client = axios.create({
baseURL: BASE_URL,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
});
And my method for post request is:
export const postRequest = (url, payload = {}) => client.post(url, payload);
And when i request i call this method:
const res = await postRequest('/login', body)
axios.create returns a client that has the property .request, not .post
Example from https://masteringjs.io/tutorials/axios/create-post
const client = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000
});
let res = await client .request({
data: {
name: 'Masteringjs.io',
email: 'Masteringjs#io'
}
});
res.data.json // ↓
// { email: 'Masteringjs#io', name: 'Masteringjs.io' }
So your code would look like this:
const client = axios.create({
baseURL: BASE_URL,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
method: "POST"
});
export const postRequest = (url, payload = {}) => client.request({ url, data: payload });
const res = await postRequest('/login', body)
You need to do this. I am using this test API https://jsonplaceholder.typicode.com/ you can cross-check my snippet response with the mentioned URL.
const client = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
});
client({
'method': 'GET',
'url': '/todos/1'
}).then((res) => console.log(res.data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
here is my javascript form handler
where i get data from the form to send it as request to API
import { Store } from './http/requests.js';
$(document).ready(function () {
$('#form_submit').submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
Store(formData);
});
});
js requests file handler
where i use customized post,get functions to send data with options that i provide on it
import { get, post } from '../helper.js';
let pageName = window.location.pathname;
pageName = pageName.slice(1, pageName.length - 5);
export const Store = (value) => {
switch (pageName) {
case 'add_car':
post('user/create_car', value, true, 'multipart/form-data')
.then((res) => {
console.log(res);
return res;
})
.catch((err) => console.log(err));
default:
break;
}
};
then the helper file where i use fetch get,post with option that i receive from "requests.js" file and provide it here
import { Local as loc } from './localStorage.js';
const API_URL = 'http://127.0.0.1:8000/api';
// token if exists in localStorage
const token = loc('get', 'token');
// POST Request
export const post = (
url,
formData,
auth = false,
type = 'application/json',
providedToken = token,
) => {
return fetch(`${API_URL}/${url}`, {
method: 'POST',
body: JSON.stringify(formData),
headers: {
'Content-Type': type,
Authorization: auth ? `Bearer ${providedToken}` : null,
},
})
.then((res) => res.json())
.then((res) => {
console.log(res);
return res;
})
.catch((err) => console.log(err));
};
and finally the Laravel API Cotroller where i tried to debug the issue
public function create_car(Request $request)
{
return (response()->json([
"files" => $_FILES,
"all Request data" => $request,
]));
}
the response i get when i send data from javascript to Laravel API
API gives me back this empty object as a response
it's seems like fetch has a problem ... anyway i just replaced fetch library with axios and everything runs perfectly
here is what i did on helper.js file
// POST Request
export const post = (
url,
formData,
auth = false,
type = 'application/json',
providedToken = token,
) => {
return axios({
method: 'POST',
url: `${API_URL}/${url}`,
data: formData,
headers: {
'Content-Type': type,
Authorization: auth ? `Bearer ${providedToken}` : null,
},
})
.then((res) => {
console.log(res);
return res.data;
})
.catch((err) => console.log(err.data));
};
This is a simple Post request using Axios inside Vue:
import axios from 'axios'
export default {
name: 'HelloWorld',
props: {
msg: String
},
mounted () {
const code = 'test'
const url = 'http://localhost:3456/'
axios.post(url, code, { headers: {'Content-type': 'application/x-www-form-urlencoded', } }).then(this.successHandler).catch(this.errorHandler)
},
methods: {
successHandler (res) {
console.log(res.data)
},
errorHandler (error) {
console.log(error)
}
}
}
The Get method works fine. But Post stay as "Pending" on Network tab. I can confirm that there is a Post method on my webservice and it return something (tested on Postman).
UPDATE
Sending code as a param:
axios(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
params: {
code : 'test'
},
}).then(this.successHandler).catch(this.errorHandler)
WEBSERVICE
server.post('/', (req, res, next) => {
const { code } = req.params
const options = {
validate: 'soft',
cheerio: {},
juice: {},
beautify: {},
elements: []
}
heml(code, options).then(
({ html, metadata, errors }) => {
res.send({metadata, html, errors})
next()
})
})
I think there's issue with your axios request structure.
Try this:
const URL = *YOUR_URL*;
axios(URL, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
data: *YOUR_PAYLOAD*,
})
.then(response => response.data)
.catch(error => {
throw error;
});
If you're sending a query param:
axios(URL, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
params: {
code: 'your_string'
},
})
if it is path variable you can set your url:
const url = `http://localhost:3456/${code}`
Let me know if the issue still persists
I also was facing the same. Network call was pending all the time and Mitigated it by passing the response back from server.js(route file) e.g(res.json(1);) and it resolved the issue