Extend JSON Server Data Provider in React-Admin so the update do not send the ID in the body - react-admin

I'm using react-admin for the first time.
When updating (PUT) my backend do not accept the ID in the body (the reference for the id is in the url: http://api.com/item/{id}).
But by default react-admin sends it.
How can I change that? I tried to extend the data provider, but I don't know how to make it modify the body:
const dataProvider = jsonServerProvider('http://localhost:8000', httpClient);
const myDataProvider = {
...dataProvider,
update: (resource, params) => {
httpClient(`${apiUrl}/${resource}/${params.id}`, {
method: 'PUT',
body: JSON.stringify(params.data),
}).then(({ json }) => ({ data: json }
)).catch(err => {
return console.log(err)
})
console.log(params.data);
},
};
export default myDataProvider;
I think I would need to change the params.data, deleting the "id", but I couldn't... always get errors.
Any suggestions?
Thanks!

Remove it from the data:
const dataProvider = jsonServerProvider('http://localhost:8000', httpClient);
const myDataProvider = {
...dataProvider,
update: (resource, params) => {
const { id, ...data } = params.data;
// don't forget to return the promise!
return httpClient(`${apiUrl}/${resource}/${params.id}`, {
method: 'PUT',
body: JSON.stringify(data),
})
.then(({ json }) => ({ data: json }))
.catch(err => {
return console.log(err)
})
},
};
export default myDataProvider;

Related

I am unable to get API data in redux store

I am trying to build an app to add and delete items. I am using an API(Link of API documentation below). I can post and get data from API to the store. But I am unable to show the saved items on UI. And the getBooks function seems to be not working. Can anyone please help me?
Link to API documentation: https://www.notion.so/Bookstore-API-51ea269061f849118c65c0a53e88a739
Here is the code, I have used.
export const addBook = (book) => async (dispatch) => {
await fetch(url, {
method: 'POST',
body: JSON.stringify(book),
headers:{
'Content-type': 'application/json; charset=UTF-8',
}
})
.then(() => dispatch({type: ADD_BOOK, book}))
}
export const removeBook = (index) => async (dispatch) => {
await fetch(`${url}/${index}`, {
method: 'DELETE',
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(() => dispatch({ type: REMOVE_BOOK, index }));
};
export const getBooks = () => async (dispatch) => {
await fetch(url)
.then((res) => res.json())
.then((book) => {
const booksArray = [];
Object.keys(book).forEach((key) => {
booksArray.push({
item_id: key,
author: book[key][0].author,
title: book[key][0].title,
category: book[key][0].category,
});
});
dispatch({ type: GET_BOOKS, booksArray});
});
};

Rtk query always returns cached data. InvalidatesTags not doing anything

Can somebody tell me why I still get the cached data after I invalidate the getUser query?
api.ts:
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({
baseUrl: REACT_APP_API_URL,
prepareHeaders: (headers, { getState }) => {
headers.set('Accept', 'application/json');
const token = (getState() as RootState).auth.token;
if (token) {
headers.set('Authorization', token);
}
return headers;
},
}),
tagTypes: [
'UserGet',
'UserPost',
],
endpoints: () => ({}),
});
userGetApi.ts:
const userGetApi = api.injectEndpoints({
endpoints: (builder) => ({
getUserData: builder.query<UserData, void>({
query: () => '/users/me',
providesTags: ['UserGet'],
}),
}),
overrideExisting: true,
});
export const { useGetUserDataQuery } = userGetApi;
userPostApi.ts:
const userPostApi = api.injectEndpoints({
endpoints: (builder) => ({
saveUser: builder.mutation<void, OnboardingEntry>({
query: (userEntries) => {
const formData = Object.keys(userEntries).reduce((formData, key) => {
formData.append(key, userEntries[key].toString());
return formData;
}, new FormData());
return {
url: '/users/update',
method: 'POST',
body: formData,
};
},
invalidatesTags: ['UserGet'],
}),
}),
overrideExisting: true,
});
export const { useSaveUserMutation } = userPostApi;
The 2 hooks I call:
const { data: { data } = {}, isLoading, isError, isSuccess } = useGetUserDataQuery();
const [saveUser, { isLoading: postIsLoading, isSuccess: postIsSuccess }] = useSaveUserMutation();
After calling saveUser(...), I get redirected to another page. When I revisit the page, I expect to see the updated user data from useGetUserDataQuery(), but I see the previous data. Even when I close and reopen the app, I still get the old data!
So what am I doing wrong here? I'm using 'ProvidesTags' & 'InvalidatesTags' as stated in the docs.
So after days of pure frustration I found the solution: Api headers.
baseQuery: fetchBaseQuery({
baseUrl: REACT_APP_API_URL,
prepareHeaders: (headers, { getState }) => {
headers.set('Accept', 'application/json');
headers.set('Cache-Control', 'no-cache');
headers.set('Pragma', 'no-cache');
headers.set('Expires', '0');
const token = (getState() as RootState).auth.token;
if (token) {
headers.set('Authorization', token);
}
return headers;
},
}),
Hopefully this answer will help others as well

data sent with vuex action return undefined

i'm using axios with vuex, i need to send data with json form to execute post request and add new row with axios, i'm using vuex, when action is trigered it doesn't keep the data and sent it on action, the data json is created on vue componment but don't send it to action to execute axios post :
Action.js:
export const addClassification = ({data}) => {
console.log('data actio:', {data})
axios
.post("/vendor/classification/save", data, {
headers: {
"Content-Type": "application/json",
// withCredentials: true //sent with cookie
Authorization: "Bearer " + Vue.$cookies.get("jwt"),
}
})
.then((res) => {
console.log('res', res)
// commit("ADD_TO_CLASSIFICATION", data);
})
.catch((err) => {
console.log(err);
});
state.js:
export default {
vendorClassificationList: [],
}
page.vue:
<BaseButton
label="Modifier"
classValue="btn-outline-primary"
#click.native="addClassificationData"
/>
data() {
return {
submitStatus: "",
name: this.$route.params.name,
id: this.$route.params.id,
code: this.$route.params.code,
jsonData:[]
};
},
methods: {
...mapActions(["addClassification"]),
addClassificationData() {
this.jsonData = JSON.stringify({
id: null,
name: this.name,
code:this.code,
active:true
})
console.log('json is', this.jsonData)
this.addClassification({
data : this.jsonData
})
},
Actions is Vuex receive the vuex context as the first param, as you can see in the docs.
In other words if you change in Action.js:
addClassification = ( {data}) => {
to
addClassification = (vuexContext, {data}) => {
it should do the trick. You can call the param vuexContext, context, destructure it if needed or call it _ if unused (as in your case), doesn't really matter, as long as it's there.
Your vuex action is wrong. You are missing the context which can use argument restructuring. Also, you probably need to send res.data within the commit instead of res, depending on what are you doing in your mutation.
actions: {
addClassification ({ commit }, payload) {
axios
.post("/vendor/classification/save", payload, {
headers: {
"Content-Type": "application/json",
// withCredentials: true //sent with cookie
Authorization: "Bearer " + Vue.$cookies.get("jwt"),
}
})
.then((res) => {
console.log('res', res)
commit("ADD_TO_CLASSIFICATION", res.data);
})
.catch((err) => {
console.log(err);
})
}
}

React Native: setState doesn't work when calling try-catch function

I tried to call APP with this code imported from another file and it worked fine:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
let formData = new FormData();
formData.append('userId', '1'); // < this is what I want to change
formData.append('key', '***'); //my key
export function getScoreFromAPI () {
return fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
}
but now I want to change my userId from 1 to an constante from Asyncstorage, so I decide to change my code to this:
constructor(props) {
super(props)
this.state = { infos: [], userId: '' }
}
componentWillMount() {
this.getScoreFromAPI().then(data => {
this.setState({ infos: data })
});
console.log(this.state.infos);
AsyncStorage.getItem(USERID_STORED)
.then((data) => {
if (data) {
this.setState({userId:data})
}
});
}
async getScoreFromAPI() {
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
try {
let response = await fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
let res = await response.json();
} catch(error) {
console.warn("errors are " + error);
}
};
with a try-catch function but when I call getScoreFromAPI() in ComponentWillMount() I can't setState with received data, I still have an empty array in info:[]
my questions:
how can I replace '1' in userId by a value in asyncstorage in the first file ?
if it isn't possible, what I have do to setState info: [] with my data reveived
I've simplified your code into a promise chain in which calling getScoreFromAPI will execute after getting the userId from AsyncStorage, then storing the response into the infos state, while returning null if there was an error, and logging the error to the console. The data was not previously returned from getScoreFromAPI, so the value would always become null. I have not tested this code, but this should give you a good base to work from:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
export default class Test {
constructor() {
this.state = {
infos: null,
userId: ''
};
}
componentDidMount() {
AsyncStorage.getItem(this.state.userId)
.then(userID => {
this.setState({ userId: userID || '' });
})
.then(() => {
return this.getScoreFromAPI();
})
.then(data => {
this.setState({ infos: data });
})
.catch(console.error);
}
getScoreFromAPI = () => {
const formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(response => {
// use response data here
return response.json();
})
.catch(e => {
console.error(e);
return null;
});
};
}
You're doing your API call before fetching your value from AsyncStorage (I know this is async but it's not very readable if you do it that way).
getScoreFromAPI doesn't return anything, that's why your setState isn't working.
You don't need to use try and catch here, promises have their own error handling mechanism (the .catch() method).
I think callbacks are more readable and lead to less bugs than using .then() in code.
This is how I would do it:
constructor(props)
{
super(props);
this.state = { infos: [], userId: '' };
this.onSuccess = this.onSuccess.bind(this);
this.onFailure = this.onFailure.bind(this);
}
componentWillMount()
{
// Get userID from local storage, then call your API
AsyncStorage.getItem(YOUR_KEY)
.then(userID=> {
if (userID)
{
this.setState({ userId : userID }, () => {
this.getScoreFromAPI(this.onSuccess, this.onFailure);
});
}
});
}
onSuccess(data)
{
this.setState({
infos : data
});
}
onFailure(err)
{
console.warn('Error ' + err);
}
getScoreFromAPI(onSuccess, onFailure)
{
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //your key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(res => res.json())
.then(json => {
onSuccess(json);
})
.catch(err => {
onFailure(err);
});
}
It's finally done. I tried this and it worked. Thank you to all of you
this is what I have done:
...
const USERID_STORED = "userid_stored";
const GSM_STORED = "gsm_stored";
...
class ScoreList extends React.Component {
constructor(props) {
super(props)
this.state = { infos: [], userId: '', gsmStored: '', }
}
componentWillMount() {
AsyncStorage.getItem(USERID_STORED)
.then(userId => {
this.setState({ userId: userId});
this.getScoreFromAPI(this.state.userId).then(data => {
this.setState({ infos: data });
});
});
AsyncStorage.getItem(GSM_STORED)
.then(gsmStore => {
this.setState({ gsmStored: gsmStore});
});
}
getScoreFromAPI (userId) {
let formData = new FormData();
formData.append('userId', userId);
formData.append('key', '***');
return fetch('https://***',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
};

Only navigate to next page when asynchronos actions are complete? React-native

So, I have a bit of a tricky situation here for me as a beginner with redux as well as react-native.
When the user loggs in, I want to update the Redux state with the user data. I call a login methond where I get a web token. Directly afterwards I want to dispatch two asynchronous actions with redux-thunk. The problem is:
By the time these actions are dispatched and I have the response from the API, I've already navigated to another screen and the data to render the list is not in the Redux state.
The Question: How can I "hold" the program until my state is updated and then navigate to the next page?
This is what happens when the user logs in:
fetch("http://10.0.2.2:8000/api/api-token-auth/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.props.email,
password: this.props.password,
})
}).then((response) => response.json()
).then((jResponse) => {
console.log(jResponse);
this._onValueChange('token_id', jResponse.token);
this.props.loginUserSuccess();
this.props.navigation.navigate('MainMenue');
}).catch((error) => {
console.log(error);
this.props.loginUserFail();
})
}
Somewhere during the login these two actions sould be dispatched completly and the state should be updated:
export const profileLoad = () => {
return (dispatch) => {
AsyncStorage.getItem('token_id')
.then((token_id) => fetch("http://10.0.2.2:8000/api/profile/", {
method: "GET",
headers: {
'Authorization': 'JWT ' + token_id
}
})
.then((response) => response.json())
.then((answer) => {
dispatch({ type: PROFILE_LOAD, payload: answer});
})
.done());
}
}
export const productsLoad = () => {
return (dispatch) => {
AsyncStorage.getItem('token_id')
.then((token_id) => {
fetch("http://10.0.2.2:8000/api/profile/products/", {
method: "GET",
headers: {
'Authorization': 'JWT ' + token_id
}
}).then((anser) => anser.json())
.then((response)=> {
dispatch ({ type: PRODUCTS_LOAD, payload: response})
})
}
).done();
}
}
Then I want to navigate the another screen andrender a list (with ListView) to display the JSON data from products and profiles.
-- > So I finally figured it out.
Solution
1.) Return promises from action creators as stated
2.) Make sure you put a callback function in the then method
export const loadAllProfileData = ({navigate}) => {
return (dispatch) => {
dispatch(profileLoad())
.then(() => dispatch(productsLoad()))
.then(() => navigate('MainMenue'))
};
}
export const profileLoad = () => {
return (dispatch) => {
return AsyncStorage.getItem('token_id')
.then((token_id) => fetch("http://10.0.2.2:8000/api/profile/", {
method: "GET",
headers: {
'Authorization': 'JWT ' + token_id
}
})
).then((response) => response.json())
.then((answer) => {
dispatch({ type: PROFILE_LOAD, payload: answer});
})
}
}
export const productsLoad = () => {
return (dispatch) => {
return AsyncStorage.getItem('token_id')
.then((token_id) =>
fetch("http://10.0.2.2:8000/api/profile/products/", {
method: "GET",
headers: {
'Authorization': 'JWT ' + token_id
}
})
).then((answer) => answer.json())
.then((response)=> {
dispatch ({ type: PRODUCTS_LOAD, payload: response})
})
}
}
You can return promises from your action creators and chain them with then. You can do that by simply adding return AsyncStorage.getItem() ... to your action creators. Then you can do:
fetch(url) //login
.then(dispatch(profileLoad))
.then(dispatch(productsLoad))
.then(this.props.navigation.navigate('MainMenue'))
.catch(err => //handle error)
Read more about promises chaining.
Edit: A simple example would be:
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import fetch from 'node-fetch';
const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const FETCH_DATA = 'FETCH_DATA';
const url = `${ROOT_URL}/users`;
function fetchData() {
return (dispatch) => {
return fetch(url)
.then(res => res.json())
.then(data => {
dispatch({
type: FETCH_DATA,
payload: data[0].name
});
})
}
}
function reducer(state = [], action) {
if (action.type === FETCH_DATA) {
console.log('Action.payload:', action.payload);
}
switch (action.type) {
case 'FETCH_DATA':
return [...state, action.payload];
default:
return state;
};
}
let store = createStore(
reducer,
applyMiddleware(thunkMiddleware)
)
store.subscribe(() =>
console.log('Store State: ', store.getState())
)
fetch(url)
.then(res => res.json())
.then(data => data)
.then(store.dispatch(fetchData()))
.then(store.dispatch(fetchData()))