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

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: {…}}

Related

How to return object from django with react?

How to send id of object with React to django and return data of the object?
You can use axios:
import axios from "axios";
getObject(id) {
return axios.get(`http://127.0.0.1:8000/api/${id}/`);
};
getObject(objectID)
.then((response) => {
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
If You need to send object data from React to Django Backend You can send POST request, like this:
createObject(data) {
return axios.post("http://127.0.0.1:8000/api/", data);
};
createObject(data)
.then((response) => {
console.log(response);
})
.catch((e) => {
console.log(e);
});
or PUT request:
updateObject(id, data) {
return axios.put(`http://127.0.0.1:8000/api/${id}/`, data);
};
updateObject(
objectID,
data
)
.then((response) => {
console.log(response);
})
.catch((e) => {
console.log(e);
});

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)
})
}, [])

How to make api call with optional payload in React JS

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(...)

resolving race condition on API call

I'm having a problem that seems to be due to an async call. I have an action that makes an API call and pushes to a Dashboard page. That API call also updates state.account.id based on the response it gives back:
const submitLogin = e => {
e.preventDefault();
props.loginAndGetAccount(credentials);
props.history.push('/protected');
e.target.reset();
}
loginAndGetAccount is coming from this action:
export const loginAndGetAccount = credentials => dispatch => {
dispatch({ type: GET_ACCOUNT_START })
axios
.post('https://foodtrucktrackr.herokuapp.com/api/auth/login/operators', credentials)
.then(res => {
console.log(res);
dispatch({ type: GET_ACCOUNT_SUCCESS, payload: res.data.id })
localStorage.setItem("token", res.data.token)
})
.catch(err => console.log(err));
}
On the Dashboard page, I have useEffect set up to make another API call dynamically based on the value held in state.account.id. However, it seems the first API call is pushing to the Dashboard page before the response comes back and updates state.account.id. Therefore, when the second API call is made there, it's passing state.account.id to that dynamic API call as undefined, which, of course, results in a failed call. How can I resolve this?
Here's what's happening:
const Dashboard = props => {
const [accountInfo, setAccountInfo] = useState({});
useEffect(() => {
console.log(props.accountId);
axiosWithAuth()
.get(`/operator/${props.accountId}`)
.then(res => {
console.log(res);
})
.catch(err => console.log(err));
}, [])
return (
<div>
<h1>This is the Dashboard component</h1>
</div>
)
}
const mapStateToProps = state => {
return {
accountId: state.account.id
}
}
export default connect(mapStateToProps, {})(Dashboard);
The root of the problem is that you are making a request here, but not
export const loginAndGetAccount = credentials => dispatch => {
dispatch({ type: GET_ACCOUNT_START })
axios
.post('https://foodtrucktrackr.herokuapp.com/api/auth/login/operators', credentials)
.then(res => {
console.log(res);
dispatch({ type: GET_ACCOUNT_SUCCESS, payload: res.data.id })
localStorage.setItem("token", res.data.token)
})
.catch(err => console.log(err));
}
waiting for it to complete here before you navigate to the next page
const submitLogin = e => {
e.preventDefault();
props.loginAndGetAccount(credentials);
props.history.push('/protected');
e.target.reset();
}
the quickest way to fix this is to returnt the promise from loginAndGetAccount and then props.history.push in the resolution of that promise...
like this:
export const loginAndGetAccount = credentials => dispatch => {
dispatch({ type: GET_ACCOUNT_START })
// return the promise here
return axios
.post('https://foodtrucktrackr.herokuapp.com/api/auth/login/operators', credentials)
.then(res => {
console.log(res);
dispatch({ type: GET_ACCOUNT_SUCCESS, payload: res.data.id })
localStorage.setItem("token", res.data.token)
})
.catch(err => console.log(err));
}
...
const submitLogin = e => {
e.preventDefault();
props.loginAndGetAccount(credentials)
.then(() => {
// so that you can push to history when it resolves (the request completes)
props.history.push('/protected');
e.target.reset();
}
.catch(e => {
// handle the error here with some hot logic
})
}

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));
}

Resources