React Redux promise error - (...).then is not a function - javascript

Had a look for this in the questions that offered but this was the closest and it didnt really address my problem.
I have a code block (detailed a little way down the page) as part of a larger fetch block.. it gets to this codeblock and also runs fine if this code block is commented out i.e it carrys out a successful fetch etc and returns a JWT no problem but... add this block in and i get the following error:
TypeError: (0 , _localStorageDropDowns.confirmSelectDataExistance)(...).then is not a function
It is referring to this function in another folder (imported correctly)..
export const confirmSelectDataExistance = () => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
return true
}
console.log('nothing in localstorage')
return false
}
simple function - returns true or false.
and here is the code block -its failing on the first line:
return confirmSelectDataExistance().then(isConfirmed => {
if (!isConfirmed) {
dispatch({ type: REQUEST_SELECT_DATA })
console.log('gets here!', isConfirmed)
const token = getJwt()
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
return saveSelectData(selectData);
}
})
From my limited experience the "confirmSelectDataExistance" is a function so why is it saying that its not?
Finally here is the whole action in its entirety so you can see how it that block is called.. as I said - comment the block out and it works perfectly..
export const requestLoginToken = (username, password) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })
const payload = {
userName: username,
password: password,
}
const task = fetch('/api/jwt', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
saveJwt(data)
return confirmSelectDataExistance().then(isConfirmed => {
if (!isConfirmed) {
dispatch({ type: REQUEST_SELECT_DATA })
console.log('gets here!', isConfirmed)
const token = getJwt()
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
return saveSelectData(selectData);
}
})
})
.catch(error => {
clearJwt()
console.log('ERROR - LOGIN!',error)
})
addTask(task)
return task
}
EDIT
I have finally got this to work after hacking away for hours.. Here is the finished action:
export const requestLoginToken = (username, password) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })
const payload = {
userName: username,
password: password,
}
const task = fetch('/api/jwt', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
saveJwt(data)
// Now check local storage for dropdown data..
if (!confirmSelectDataExistance()) {
dispatch({ type: REQUEST_SELECT_DATA })
const token = JSON.stringify(data)
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
}
})
.catch(error => {
clearJwt()
console.log('ERROR - LOGIN!', error)
})
addTask(task)
return task
}
and here is the function it calls:
export const confirmSelectDataExistance = () => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
return true
}
console.log('nothing in localstorage')
return false
}
The one thing I changed from the other attempts is that I used "data" instead of calling "getJwt()". I then used the line:
const token = JSON.stringify(data)
to obtain the JWT I just got.
In the end I used #Karin s answer and ran with that. (upvoted by me)

The error is not saying that confirmSelectDataExistance is not a function, it's saying that then isn't a function on what is returned from it, which is a boolean (it would be equivalent to false.then(...), which doesn't work).
If seems like you're trying to use then as a conditional. In that case a simple if statement should work:
if (confirmSelectDataExistance()) {
// do things if it returns true
} else {
// do things if it returns false
}

export const confirmSelectDataExistance = () => {
return new Promise(function (resolve, reject) {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
resolve(true)
}
console.log('nothing in localstorage')
reject(false)
})
}

Try something like this:
export const confirmSelectDataExistance = new Promise((resolve, reject) => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME);
const statesJson = localStorage.getItem(STATES);
const suburbLocationsJson = localStorage.getItem(LOCATIONS);
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage');
resolve(true);
}
console.log('nothing in localstorage');
reject(false); // or resolve(false) if you want handle this situation inside then block also
});

Related

AsyncStorage works only when app is reloaded

i set my values in Async storage while logging
fetch('http://xxxxx/xxxx/getUserDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: this.state.userEmail,
})
})
.then((response) => response.json())
.then((responseJson) => {
const name = responseJson[0]['name'];
const profilePicture = responseJson[0]['profile_picture'];
const userId = responseJson[0]['id'];
const loginMode = responseJson[0]['login_mode'];
AsyncStorage.setItem('active', 'true');
AsyncStorage.setItem('userEmail', this.state.userEmail);
AsyncStorage.setItem('name', name);
AsyncStorage.setItem('profilePicture', profilePicture);
AsyncStorage.setItem('userID', userId);
AsyncStorage.setItem('loginMode', loginMode)
setTimeout(async () => {
this.setState({ isLoading: false })
this.props.navigation.navigate('userScreen');
}, 500)
})
.catch((error) => {
console.log(error);
})
}
and delete those while logging out.
fetch('https://xxxxxx/xxxx/userLogout.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userEmail
})
}).then((response) => response.json())
.then(async (responseJson) => {
try {
const keys = await AsyncStorage.getAllKeys();
await AsyncStorage.multiRemove(keys);
this.props.navigation.toggleDrawer();
this.setState({ isLoading: false })
this.props.navigation.navigate('loginScreen');
} catch (error) {
console.log("Error clearing app data");
}
}).catch((error) => {
console.log(error);
})
but again if i login with new user the old user details is shown in login page. if i reload my app the new values stored in async storage is shown why this is happen and this is not happening?
I am using the AsyncStorage here.
async componentDidMount() {
const userEmail = await AsyncStorage.getItem('userEmail');
const name = await AsyncStorage.getItem('name');
const profilePicture = await AsyncStorage.getItem('profilePicture');
const userID = await AsyncStorage.getItem('userID');
this.getWish();
this.getAddFunction();
this.setState({ userEmail })
this.getResumeVideo(userEmail);
this.getDemoVideo();
this.getClass();
this.setState({
userEmail,
name,
profilePicture,
userID
})
this.getNotificationCount(userID);
Orientation.lockToPortrait();
this._unsubscribe = this.props.navigation.addListener('focus', () => {
this.getAddFunction();
this.getDemoVideo();
this.getResumeVideo(this.state.userEmail);
this.getClass();
this.getNotificationCount(userID);
});
}
The only place you are calling setState and tells react it should assign new value to state (and render...) it at componentDidMount, therefore React don't know it should render again.
When assigning new value to AsyncStorage you might also call setState
fetch('http://xxxxx/xxxx/getUserDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: this.state.userEmail,
})
})
.then((response) => response.json())
.then((responseJson) => {
const name = responseJson[0]['name'];
const profilePicture = responseJson[0]['profile_picture'];
const userId = responseJson[0]['id'];
const loginMode = responseJson[0]['login_mode'];
AsyncStorage.setItem('active', 'true');
AsyncStorage.setItem('userEmail', this.state.userEmail);
AsyncStorage.setItem('name', name);
AsyncStorage.setItem('profilePicture', profilePicture);
AsyncStorage.setItem('userID', userId);
AsyncStorage.setItem('loginMode', loginMode)
setTimeout(async () => {
this.setState({ isLoading: false })
this.props.navigation.navigate('userScreen');
}, 500)
// here
this.setState({
name,
profilePicture,
userID
})
})
.catch((error) => {
console.log(error);
})
}

React Redux Thunk with callback to another function -- TypeError: Cannot read property 'then' of undefined

I am using react+redux.
I have a modal form with data and images and on success I need to close the modal else display error returned from redux. In the dispatch function I have 1 more callback function to store images to S3. I am returning promise from the redux-thunk but I keep getting "TypeError: Cannot read property 'then' of undefined".
Component
handleSubmit = e => {
e.preventDefault();
if(this.isFieldEmpty()){
this.setState({ message: "All fields are mandatory with at least 1 pic" });
return;
} else {
this.setState({ message: "" });
}
const data = {
name: this.state.name,
description : this.state.description,
points : this.state.points,
attributes : this.state.attributes,
images : this.state.images,
created_by: localStorage.getItem('id'),
}
this.props.createItem(data).then(() => {
this.hideModal();
})
}
const mapDispatchToProps = dispatch => {
return {
createItem: data => {
return dispatch(createItem(data))
},
};
};
Action
const saveItemImages = (images,successcb, failurecb) => {
if(images.length > 0){
const formData = new FormData();
for(var x = 0; x<images.length; x++) {
formData.append('image', images[x])
}
const token = localStorage.getItem('token');
fetch(`${backendUrl}/upload/item-images/`, {
method: "POST",
headers: {
'Authorization': `Bearer ${token}`
},
credentials: 'include',
body: formData
})
.then(res => {
if(res.status === 200){
res.json().then(resData => {
successcb(resData.imagesUrl);
});
}else{
res.json().then(resData => {
failurecb(resData.message);
})
}
})
.catch(err => {
console.log(err);
});
} else {
successcb([]);
}
}
export const createItem = data => { return (dispatch) => {
saveItemImages(data.images, imagesUrl => {
data.images = imagesUrl;
return fetch(`${backendUrl}/admin/createItem`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.token}`
},
credentials: 'include',
body: JSON.stringify(data)
})
.then(res => {
if(res.status === 200){
res.json().then(resData => {
dispatch({
type: ADMIN_CREATE_ITEM_SUCCESS,
payload: resData
})
return true;
});
}else{
console.log("Save failed");
res.json().then(resData => {
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: {
message: resData.message
}
})
})
}
})
.catch(err => {
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: {
message: `Internal Error -- ${err}`
}
})
});
}, failedMessage => {
let payload = {responseMessage: failedMessage}
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: payload
})
});
};
};
Thanks in advance for any help
You should return a Promise to create async flow for the action like this:
export const createItem = data => dispatch => new Promise((resolve, reject) => {
// do something was a success
resolve();
// do something was a fail
reject();
});

In react, how to update state after doing a fetch?

I have a state which is an empty array:
constructor(props) {
super(props);
this.state = {
test_steps: [],
};
}
I need to fill up that state with the following data that get when I do a GET request:
See image
UPDATED:
export function copyTestScenarioLog(tSL) {
console.log("\nCalled copyTestScenarioLog");
let url = config.base_url + `/test_scenario_logs`;
return fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + getUserToken() },
body: JSON.stringify({
_id: tSL._id['$oid']
})
})
.then(res => res.json())
.then(data => {
getTestStepLogs(data)
return data;
})
.catch(err => console.log(err));
}
export function getTestStepLogs(data) {
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
})
.then(res => res.json())
.then(data => {
console.log(data)
return data
})
.catch(err => console.log(err));
}
How do I update my state after doing a GET fetch?
This is full react component code, you see how I call your funciton in componentDidMount, and in here I pass 'this' as an argument to copyTestScenarioLog.
import React, { Component } from 'react';
import copyTestScenarioLog from './copyTestScenarioLog';
class Component1 extends Component {
constructor(props) {
super(props);
this.state = {
test_steps: []
};
}
componentDidMount() {
var reactComponent = this;
copyTestScenarioLog('i dont konw that is tsl', reactComponent);
}
render() {
return (
<div></div>
);
}
}
export default Component1;
In 'copyTestScenarioLog', I get that ( refers to react component), and use setState function in react.
export function copyTestScenarioLog(tSL, reactComponent) {
console.log("\nCalled copyTestScenarioLog");
let url = config.base_url + `/test_scenario_logs`;
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + getUserToken() },
body: JSON.stringify({
_id: tSL._id['$oid']
})
})
.then(res => res.json())
.then(data => {
getTestStepLogs(data)
reactComponent.setState({
test_steps: data
});
return data;
})
.catch(err => console.log(err));
}
But basically I don't use this approach, I just wanted to show that how its done, I usually use await/async or function generators, because they are better approaches. Search about them and learn to use them.
you can pass onSuccess function into your getTestStepLogs and update your state.
export function getTestStepLogs(data , onSuccess) {
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
}).then(resp => {
if (onSuccess)
onSuccess(resp);
}).catch(err => console.log(err));
}
and when you call getStepLogs pass onSuccess as props:
this.props.getTestStepLogs(data , (resp)=>{
this.setState({test_steps:resp});
})
if you are using the get call at multiple place, you can be little generic and try this approach.
//return here does not do anything right now
export function getTestStepLogs(data) {
return new Promise(function(resolve, reject){
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
})
.then(res => res.json())
.then(data => {
console.log(data)
resolve(data);
})
.catch(err => {console.log(err);
reject(err);
});
})
}
async componentDidMount() {
let data = await copyTestScenarioLog();
//now set it to state
}
For an async call, there are three states. Call initiation, call success and call failure. Say "isLoading" represents the status of the call being running in the background.
Initially =>
{
isLoading : false,
data : '',
err : ''
}
Call initiated =>
{
isLoading : true,
data : '',
err: ''
}
Call success =>
{
isLoading : false,
data : response.data
err: ''
}
Call failed =>
{
isLoading :false,
data : '',
err: err
}
Usually, the GET calls of a component are made in componentDidMount. It is also the suggested way as per the react documentation.
componentDidMount(){
//Call Initiation
this.setState({
isLoading : true,
data : '',
err: ''
});
makeApiCall(api).
then((response) => {
this.setState({
isLoading : false,
data : response.data
err: ''
});
},
(err) => {
this.setState({
isLoading :false,
data : '',
err: err
})
})
.catch((err) => {
this.setState({
isLoading :false,
data : '',
err: err
})
})
}

React-Redux syntax error "," expected

New to this.
...and this is probably very simple. I have looked at the code for the const "selectData" and I cannot find where a comma is suppose to go. Here is the entire file:
export const requestLoginToken = (username, password) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })
const payload = {
userName: username,
password: password,
}
const task = fetch('/api/jwt', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
saveJwt(data)
selectData()
})
.catch(error => {
clearJwt()
dispatch({ type: ERROR_LOGIN_TOKEN, payload: error.message })
})
addTask(task)
return task
}
const selectData = () => {
dispatch({ type: REQUEST_SELECT_DATA })
const token = jwt.access_token
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const selectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers,
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: data })
.catch(error => {
clearJwt()
dispatch({ type: ERROR_SELECT_DATA, payload: error.message })
})
}
}
The error is on the very last curly bracket and it says:
Unexpected token, expected , (72:0)
line 72 is the last curly bracket.
If I remove the const expression that is "selectData" its OK - no errors. The error only appears when I add in that block of code... i.e its in the following:
const selectData = () => {
dispatch({ type: REQUEST_SELECT_DATA })
const token = jwt.access_token
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const selectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers,
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: data })
.catch(error => {
clearJwt()
dispatch({ type: ERROR_SELECT_DATA, payload: error.message })
})
}
}
Why is this block of code causeing an error?
You forgot a ) on the last then:
.then(data => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: data })
.catch(error => {
clearJwt()
dispatch({ type: ERROR_SELECT_DATA, payload: error.message })
})
}) // <--- here
And you should always use ;. I recommend you to use a linter to check your code, like ESLint

Javascript: Fetch DELETE and PUT requests

I have gotten outside of GET and POST methods with Fetch. But I couldn't find any good DELETE and PUT example.
So, I ask you for it. Could you give a good example of DELETE and PUT methods with fetch. And explain it a little bit.
Here is a fetch POST example. You can do the same for DELETE.
function createNewProfile(profile) {
const formData = new FormData();
formData.append('first_name', profile.firstName);
formData.append('last_name', profile.lastName);
formData.append('email', profile.email);
return fetch('http://example.com/api/v1/registration', {
method: 'POST',
body: formData
}).then(response => response.json())
}
createNewProfile(profile)
.then((json) => {
// handle success
})
.catch(error => error);
Ok, here is a fetch DELETE example too:
fetch('https://example.com/delete-item/' + id, {
method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))
For put method we have:
const putMethod = {
method: 'PUT', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
body: JSON.stringify(someData) // We send data in JSON format
}
// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
Example for someData, we can have some input fields or whatever you need:
const someData = {
title: document.querySelector(TitleInput).value,
body: document.querySelector(BodyInput).value
}
And in our data base will have this in json format:
{
"posts": [
"id": 1,
"title": "Some Title", // what we typed in the title input field
"body": "Some Body", // what we typed in the body input field
]
}
For delete method we have:
const deleteMethod = {
method: 'DELETE', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
// No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
In the url we need to type the id of the of deletion: https://www.someapi/id
Just Simple Answer.
FETCH DELETE
function deleteData(item, url) {
return fetch(url + '/' + item, {
method: 'delete'
})
.then(response => response.json());
}
Here is good example of the CRUD operation using fetch API:
“A practical ES6 guide on how to perform HTTP requests using the Fetch API” by Dler Ari https://link.medium.com/4ZvwCordCW
Here is the sample code I tried for PATCH or PUT
function update(id, data){
fetch(apiUrl + "/" + id, {
method: 'PATCH',
body: JSON.stringify({
data
})
}).then((response) => {
response.json().then((response) => {
console.log(response);
})
}).catch(err => {
console.error(err)
})
For DELETE:
function remove(id){
fetch(apiUrl + "/" + id, {
method: 'DELETE'
}).then(() => {
console.log('removed');
}).catch(err => {
console.error(err)
});
For more info visit Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.
Some examples:
async function loadItems() {
try {
let response = await fetch(`https://url/${AppID}`);
let result = await response.json();
return result;
} catch (err) {
}
}
async function addItem(item) {
try {
let response = await fetch("https://url", {
method: "POST",
body: JSON.stringify({
AppId: appId,
Key: item,
Value: item,
someBoolean: false,
}),
headers: {
"Content-Type": "application/json",
},
});
let result = await response.json();
return result;
} catch (err) {
}
}
async function removeItem(id) {
try {
let response = await fetch(`https://url/${id}`, {
method: "DELETE",
});
} catch (err) {
}
}
async function updateItem(item) {
try {
let response = await fetch(`https://url/${item.id}`, {
method: "PUT",
body: JSON.stringify(todo),
headers: {
"Content-Type": "application/json",
},
});
} catch (err) {
}
}
Let me simplify this, you can straight up copy the code.
This is for PUT method :
fetch('https://reqres.in/api/users', + id {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'user'
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
and this is for DELETE :
fetch('https://reqres.in/api/users' + id, {
method: 'DELETE',
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
Note: I'm using dummy api here.
This is what worked for me when using the PUT method. This method allows me to effectively update the 1st item using my first name:
fetch('https://reqres.in/api/users', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: 1,
first_name: 'Anthony'
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
Here are examples for Delete and Put for React & redux & ReduxThunk with Firebase:
Update (PUT):
export const updateProduct = (id, title, description, imageUrl) => {
await fetch(`https://FirebaseProjectName.firebaseio.com/products/${id}.json`, {
method: "PATCH",
header: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title,
description,
imageUrl,
}),
});
dispatch({
type: "UPDATE_PRODUCT",
pid: id,
productData: {
title,
description,
imageUrl,
},
});
};
};
Delete:
export const deleteProduct = (ProductId) => {
return async (dispatch) => {
await fetch(
`https://FirebaseProjectName.firebaseio.com/products/${ProductId}.json`,
{
method: "DELETE",
}
);
dispatch({
type: "DELETE_PRODUCT",
pid: ProductId,
});
};
};
const DeleteBtn = (id) => {
fetch(`http://localhost:8000/blogs/${id}`, {
method: "DELETE"
})
.then(() => {
navigate('/');
});
}
<button onClick={(event) => { DeleteBtn(blog.id)} }>delete</button>

Categories