How to make api call with optional payload in React JS - reactjs

I am trying to call API in React JS with AXIOS. I need to send payload as optional when productID has value.
This is my service.js file
fetchProducts: (payload) => put(`/products`, payload),
fetchProductsProductID: (params, payload) => put(`/products`, payload, { params }),
products.js
useEffect(() => {
if (productID) {
CommonSrv.fetchProductsProductID(
{ productID: productID },
{
data: data,
},
)
.then((resp) => {
console.log(resp)
})
.catch((err) => {
console.log(err)
});
} else {
CommonSrv.fetchProducts({ data: data })
.then((resp) => {
console.log(resp)
})
.catch((err) => {
console.log(err)
});
}
}, [])
within the then and catch blocks same conditions I need to use. Because of productID, I am duplicating my code a lot how can I simply this code.

You can try something like that!
(productID ?
CommonSrv.fetchProductsProductID(
{ productID: productID },
{
data: data,
},
)
:
CommonSrv.fetchProducts({ data: data }))
).then(.....).catch(...)

Related

How to GET data of specific id from Realtime database in firebase

Here how to fetch specific object when we are not sure of id
useEffect(() => {
fetch("https://expensetracker-16e15-default-rtdb.firebaseio.com/expenses.json")
.then((res) => {
if (res.ok) {
// console.log(res);
return res.json();
}
}).then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
})
}, []);
Response I am getting is like this -
{-N8u3cUpSV56CWFy01Rf: {…}, -N8u5-evkjPcZmo4kpSG: {…}}

How do you save/post using axios correctly

I using Spring boot has backend and react-redux has frontend. The problem is where I try too save my data to my db the first click just save my first entity out of seven. After the second click it works normal and afterwards it works normal. I have try useEffect still the same problem.
export const setChecklist = (Checklist) => {return (dispatch) => {
console.log(Checklist);
axios
.post("http://localhost:8081/api/checklist/addList", Checklist)
.then((response) => {
console.log(response);
dispatch({
type: SET_CHECKLIST,
payload: response.data,
});
})
.catch((error) => {
console.log(error);
});
};
};
try this code:
export const setChecklist = async (Checklist) => {
const response = await axios
.post("http://localhost:8081/api/checklist/addList", Checklist)
.then((response) => {
console.log(response);
dispatch({
type: SET_CHECKLIST,
payload: response.data,
});
})
.catch((error) => {
console.log(error);
});
}
useEffect(() => {
setChecklist ()
.then((res) => {
setChecklist(res)
})
.catch((e) => {
console.log(e)
})
}, [])

React dropdown fetch from API

I want to build "React Dropdown", which will give me options to select user while I type first letters of his name.
Users data is coming from my backend API in JSON format.
// http://localhost:5000/users
{
"users": [
{
"company_id": 1,
"name": "Sally Mae"
},
{
"company_id": 2,
"name": "Johnathan Ives"
},
{
"company_id": 3,
"name": "John Smith"
}
]
}
here's my fetch part, but I can't fetch, but my server is running, this is the code
fetchData = (inputValue, callback) => {
if (!inputValue) {
callback([]);
} else {
setTimeout(() => {
fetch("http://127.0.0.1:5000/users/" + inputValue, {
method: "GET",
})
.then((resp) => {
console.log(resp);
return resp.json()
})
.then((data) => {
const tempArray = [];
data.forEach((users) => {
console.log(tempArray);
tempArray.push({ label: `${users.name}`, value: `${users.name}`});
console.log(tempArray);
});
callback(tempArray);
})
.catch((error) => {
console.log(error, "catch the hoop")
});
});
}
}
appreciate any help !
I think what you misunderstand here is that callback, of your loadOptions prop, is where you wrap your retrieval method.
const getData = (inputValue) =>
fetch('http://127.0.0.1:5000/users/' + inputValue, {
method: 'GET',
})
.then((resp) => resp.json())
.then((data) =>
data.map((user) => ({ label: user.name, value: user.name }))
)
.catch((error) => {
console.log(error, 'catch the hoop');
});
const fetchData = (inputValue, callback) => {
if (!inputValue) {
callback(Promise.resolve([]));
} else {
callback(getData(inputValue));
}
};

How can I dynamically rerender my api to my webpage?

So I have this api and I am making a get request in my ComponentDidMount() to dynamically render it to my page and it works. The issue I am facing is when I make a post request to add items to the list, it does not show on my webpage unless I refresh it. The backend is my data.json so I don't know if that is the problem but essentially when I make a post request, I am adding data to my data.json and I want that to rerender on my page without me refreshing it.
componentDidMount() {
axios.get("/api/workboard")
.then(res => {
res.data["boardLists"].map((item, key) => {
// console.log(Object.keys(item)[0])
this.setState(prevState => ({
data: [...prevState.data, item],
titles: [...prevState.titles, Object.keys(item)[0]]
}))
})
// console.log(this.state.titles)
// console.log(this.state.data)
}).catch(err => console.log(err))
}
addListItemHandler = () => {
axios({
method: 'post',
url: 'api/workboard/0/list',
data: {
title: "Untitled" ,
description: "No Description"
}
})
.then(res => {
console.log(res)
})
.catch(err => console.log(err));
}
render() {
let board = this.state.data.map((item, key) => {
return <WorkBoardContainer
key={key}
title={item[this.state.titles[key]]["title"]}
listItems={item[this.state.titles[key]]["list"].map((i) => {
return i["title"]
})}
/>
})
return (
<div className={classes.App}>
<AddButton addListItemHandler={this.addListItemHandler}/>
{board}
</div>
);
}
Try moving the fetching part as a seperate function and call it again once the post request is done.
componentDidMount() {
// fetch data when component is mounted
this.fetchData();
}
fetchData = () => {
axios.get("/api/workboard")
.then(res => {
res.data["boardLists"].map((item, key) => {
this.setState(prevState => ({
data: [...prevState.data, item],
titles: [...prevState.titles, Object.keys(item)[0]]
}))
})
}).catch(err => console.log(err))
}
addListItemHandler = () => {
axios({
method: 'post',
url: 'api/workboard/0/list',
data: {
title: "Untitled" ,
description: "No Description"
}
})
.then(res => {
console.log(res);
// fetch data again once post is done.
this.fetchData();
})
.catch(err => console.log(err));
}

Cannot read property `.then` of undefined with axios and react in actions

I am using axios in an action and trying to call that action with a chaining action. I will show what I am trying to do here:
this.props.fetchOffers().then(() => {
this.props.filter(this.props.filterOption);
});
But I get an error: Cannot read property 'then' of undefined.
What I do not get is that right below this function I have another action that is doing this exact same thing and working just fine.
this.props.sortOffers(value).then(() => {
this.props.filter(this.props.filterOption);
});
Here is a working version of this.
Here is the actions file:
import axios from 'axios';
import { reset } from 'redux-form';
import { FETCH_OFFERS, SORT_OFFERS, FETCH_OFFER, GET_FILTER, PAYMENT_TYPE } from './types';
export function paginateOffers(indexPosition, numberOfItems) {
return (dispatch) => {
axios
.get('/API/offers/pagination', {
params: {
position: indexPosition,
number: numberOfItems,
},
})
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((error) => {
console.error(error);
});
};
}
export function fetchOffers() {
return dispatch => {
axios
.get('/API/offers')
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((err) => {
console.error(err);
});
};
}
export function fetchOffer(id) {
return (dispatch) => {
axios
.get(`/API/offers/${id}`)
.then((response) => {
dispatch({ type: FETCH_OFFER, payload: response.data.result });
})
.catch((err) => {
console.error(`ERROR: ${err}`);
});
};
}
export function sortOffers(params) {
const { price, title, category, type } = params;
return dispatch =>
axios
.get('/API/offers/sort', {
params: { price, title, category, type },
})
.then((response) => {
dispatch({
type: SORT_OFFERS,
payload: response.data,
sortOptions: params,
});
dispatch({
type: PAYMENT_TYPE,
payment: type,
});
dispatch(reset('sorter'));
})
.catch((err) => {
console.error(err);
});
}
export function getFilterOption(option) {
return (dispatch) => {
dispatch({
type: GET_FILTER,
option,
});
};
}
You aren't returning a promise in your fetchOffers action creator. Notice the subtle difference in how you've declared your fat-arrow function.
Try this:
export function fetchOffers() {
return dispatch =>
axios
.get('/API/offers')
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((err) => {
console.error(err);
});
}

Resources