Is this a thunk? - reactjs

I was googling about Redux thunk and I kind of get the gist of what it's used for and how to make one and as I was about to start making it, I just realized that I may have already made one. I say may because I based my code from boilerplate code made by visual studio when I created a react app using asp.net core as a backend. The code in question:
editLecture: (lecture) => (dispatch) => {
dispatch({ type: EDITING_LECTURE, payload: lecture })
const url = `api/lecture/${lecture.topicID}`
const response = fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(lecture)
}).then(res =>
res.json()
).then(json =>
dispatch({ type: EDITED_LECTURE, payload: json })
)
}
So yeah, is this a thunk? PS: I'm a JS/React/Redux noob so if this comes out as an obvious answer I'm sorry..

Related

Host images on imgbb sometimes showing error

I upload images on one of reactjs project and host on imgbb but sometimes posting is working successfully and sometimes showing error.message: "Can't get target upload source info".
What's the problem actually ?
const [coverPhoto, setCoverPhoto] = useState([]);
const onChangeCover = (data) => {
setCoverPhoto(data)
const imgAPIKey = 'c83daa0cd70c09ca51b747864c4a22e1'
const image = data[0].file
const formData = new FormData()
formData.append('image', image)
const url = `https://api.imgbb.com/1/upload?key=${imgAPIKey}`
fetch(url,
{
method: "POST",
body: formData
})
.then(res => res.json())
.then(async result => {
console.log('imgbbCover', result)
const coverPhoto = result.data.url
await fetch(`http://localhost:5000/profiles/${email}`,
{
method: 'PUT',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({ coverPhoto })
})
})
}
see the console
Finally I've find a reason not posting the images properly sometimes is actually the freemium version has some limitations, one is not hosting every time properly...
Also tried the Cloudinary free hosting and found the same issue .

React SPA: the best way to store auth token?

I know this question has been asked many times but there is no clear answer so far and the suggested options (cookies, local storage etc..) have all pros and cons. I'm new to React SPA and I'm very confused about the right method to adopt.
For now I've based my application on the "cookie-to-header token" premise.
The API I work with returns a token meant to be used with the Authorization header for the POST PUT and DELETE requests.
So on the login page a cookie is created in order to store the token value:
const login = { email, password };
const [error, setError] = useState(null);
fetch('https://apidomain.net/api/login', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(login)
}).then((res) => {
if (!res.ok) {
throw Error('Could not fetch the data for this resource. Status: '+res.status+' Message: '+res.statusText);
}
return res.json();
})
.then((data) => {
document.cookie = "auth_token="+data.auth_token;
}).catch((err) => {
setError(err.message);
});
Then, the token value is retrieved by Javascript whenever a POST PUT or DELETE request is sent:
fetch('https://apidomain.net/api/post/4', {
method: 'DELETE',
headers: { 'Authorization': 'Bearer '+getAuthToken()}
})
It works fine but is it safe ?
Is there a better way to do that ?

How can I share local image to Firebase and then be able to retrieve whatever device I sign in in React Native?

I'm trying to post images to Firebase real-time database. Until now, I've successfully done that, the images can be shown but only when I still connect the app and not yet reload
I know the reason is because the uri I post on database has the type like this:
content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F58/ORIGINAL/NONE/image%2Fjpeg/484166561
Here's the code in Redux action for adding a post:
export const addPost = (postImage, date, description, checkin_location) => {
return async (dispatch, getState) => {
const token = getState().auth.user.token;
const userId = getState().auth.user.uid;
const response = await fetch(
`https://..../users/${userId}/posts.json?auth=${token}`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
credentials: 'same-origin',
body: JSON.stringify({
postImage,
date,
description,
checkin_location,
})
});
const resData = await response.json();
console.log(resData);
if(!response.ok){
console.log("reponse isn't ok in post action ", response)
};
dispatch({
type: ADD_POST,
postData:{
id: resData.name,
ownerId: userId,
postImage,
date,
description,
checkin_location
}
})
}
}
What should I do in order to achieve that?
Or to be precise, how can I convert that uri link to be say an url or at least a type that Image component can display even when I reload or sign in by another device
I'm using real-time database and heard of Firestore and Cloud Functions but haven't used it yet
PLEASE HELP

Cant api connection doesnt work on production react native

Before building the react native app to production, I was able to log in and I could get error messages for any errors but after building to apk, I ran the app on my android phone but It didn't work.
I am fetching the user login like this;
import { userTypes } from '../../types';
const { USER_LOGIN } = userTypes;
const SERVER_URL = "http://localhost:8080/api/v1";
const loginAction = (userdata) => dispatch => {
fetch(`${SERVER_URL}/auth/signin`,{
method: 'POST',
headers: {
'content-type' : 'application/json',
},
body: JSON.stringify(userdata)
})
.then(res => res.json())
.then(data =>(
dispatch({
type: USER_LOGIN,
payload: data
})))
}
export {
loginAction
};
Is there a proper way to use api connections both on development and production.
I guess you are using android 9. If it's the case try with this:
Add in your main AndroidManifest.xml
<manifest xmlns:tools="http://schemas.android.com/tools">
<application android:usesCleartextTraffic="true" tools:targetApi="28"> </application>
</manifest>

axios doesn't send post data to the back-end

I'm new to react and.my problem is that i'm going to make a post request to my node back-end. using react-redux and axios. the thing is my back-end doesn't even hit the request. and no action on the network tab in the browser ether
I have tried lots of another answers but doesn't work
this code is in my redux action page
export const postNominationPayments = function
postNominationPayments(candidatePayments) {
let nominationPayments = {
depositor:candidatePayments.depositor,
depositAmount:candidatePayments.depositAmount,
depositeDate:candidatePayments.depositeDate,
filePath:candidatePayments.filePath,
status:candidatePayments.status,
nominationId:candidatePayments.nominationId
};
return function (dispatch) {
console.log("**",nominationPayments);
var headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
axios
.post(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
.then(response => {
console.log("))))))))))))",response);
// dispatch({
// type: POST_NOMINATION_PAYMENTS,
// payload: response.data
// })
})
.catch(error => {
console.log("===",error);
// dispatch({ type: AUTH_FAILED });
// dispatch({ type: ERROR, payload: error.data.error.message });
});
};
}
post data is coming as expected.also the back works correctly using postman. but it's not working.
couldn't think of a solution.
what is wrong with my code?
thanks in advance
It should be
axios.post(
`${API_BASE_URL}/nominations/payments`, nominationPayments,
{headers: headers}).
One can drop headers section as well a default is application/json
The way you are passing data to axios post request is incorrect. You need to pass something like below
Change
axios(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
To
axios.post(
`${API_BASE_URL}/nominations/payments`,
nominationPayments,
{
headers: headers
}
)
axios.get and axios.post takes different kind of arguments and could be hard to remember.
So I usually just stick to the more verbose way:
axios({
method: 'post',
url: `${API_BASE_URL}/nominations/payments`,
data: {
nominationPayments
},
headers
})
.then(response => {
// ...
})
.catch(error => {
// ...
})
Have you checked whether your MongoDB server is up and running?
In my case, my React server was running, however, my MongoDB servers were not. I ran both simultaneously and was able to post data to the back end.

Resources