change api fetch into axios call - reactjs

i am trying to change the api fetch into axios get method i dont know how to do that
const fetchApi = () => {
const request = getAllActivityData();
request
.api({
params: {
customer,
},
})
i want to call api like this using axios
i have added full code in codesandbox it will be helpfull if u can edit the codesand box and make it working
useEffect(() => {
const config = {
headers: {
Authorization: `token
},
};
axios.get("customer/get-all-activity-data/?customer=22", config)
.then((res) => {
console.log(res.data);
});
code sandbox
https://codesandbox.io/s/upbeat-jasper-2jmri?file=/src/App.js:3137-3298
what i have tryed the data is not showning but there are no error .
i am getting data in postman
https://codesandbox.io/s/gifted-montalcini-j7nv7?file=/src/App.js

Do you mean something like this, using async await...
const axiosCallFn = async () => {
let url = '...'
let config = {
headers: {
token: '...'
}
}
try {
let resp = await axios.get(url, config)
return resp.data
} catch(e) {
throw e
}
}
// import the function into your component and use it like so
axiosCallFn()
.then((data) => {
// your functionality here.
})
.catch(() => {
// your error functionality here.
})
and then you can call your axiosCallFn in your useEffect.

Related

async function in react component isn't working when triggered from the axios request

network.services.js
axiosCall = (axiosURL) => {
// const axiosURL = "https://api.github.com/user"
axios.get(axiosURL, {
headers: {
'Authorization': `qwdvryjutmnevw`,
}
}).then((res) => {
console.log(res.data);
return res.data;
}).catch((error) => {
throw error.message;
// console.error(error);
// toast.error(error.message);
})
}
component.js
const getData = async () => {
const asyncExample = async () => {
const result = await networkServices.axiosCall("/api/v1/calendars");
const responseData = await result;
console.log(responseData);
return responseData;
}
const data = asyncExample()
data.then(function(result) {
console.log(result); // "Some User token"
})
}
Trying to get data from service to my component in const result, console form service is consoling data but component is always returning undefined instead of data from the service file. SetTimeout function is also not working in component.
You have many mistakes. I advise you to take a look at documentation about Promises
First one:
You don't return data in axiosCall
A way to return data:
axiosCall = (axiosURL) => new Promise((resolve, reject) => {
axios.get(axiosURL, {
headers: {
'Authorization': `yourTokenHere`,
}
}).then((res) => {
// return a response data
resolve(res.data);
}).catch((error) => {
// return only error message
reject(error.message);
})
})
to use axiosCall:
try {
// don't forgot to configure axios with base url
const data = await axiosCall('/api/v1/calendars');
// do something with your data
} catch (e) {
// do something with error message
console.log(e);
}
Second:
Your make mistakes when call async function
Look at this example:
const getData = () => {
networkServices
.axiosCall("/api/v1/calendars")
.then(function(result) {
// when promise resolve
console.log(result);
})
.catch(error => {
// when promise reject
console.log(error)
})
}

Updating useEffect api call url with user inputs

I'm working on a project, where I need to update a datachart with user inputted dates. I'm having trouble on how to update the url inside the useEffect hook. Here's my relevant code:
const finalUrl =`${apiUrl}id=${id}&timing=${time}&start=${finalStart}&end=${finalEnd}`;
console.log(finalUrl);
useEffect(() => {
axios
.get<AxiosResponse>(finalUrl, {
headers: {
"Content-Type": "application/json"
}
})
.then(response => {
setData(response);
})
.catch(error => {
console.log(error);
});
}, []);
console.log(data);
Everything looks good until i get to the axios call. I cannot get useEffect to use the updated url. Logging the response data just gives the same every time. All values inside "finalUrl" are coming from the user.
I'm going to assume that apiUrl and id never change, but that all the other things you're using in the API URL are inputs from the user.
If so, you need to rebuild the URL in the useEffect callback, and make the callback dependent on those user inputs, like this:
useEffect(() => {
const finalUrl =`${apiUrl}id=${id}&timing=${time}&start=${finalStart}&end=${finalEnd}`;
axios
.get<AxiosResponse>(finalUrl, {
headers: {
"Content-Type": "application/json"
}
})
.then(response => {
setData(response);
})
.catch(error => {
console.log(error);
});
}, [time, finalStart, finalEnd]);
The callback will be called again when time, finalStart, or finalEnd change.
Note that you also need to disregard or cancel previous requests when the dependencies change, even if the request hasn't been completed yet. I don't use axios but as I understand it has a "cancel/cancellation token" you can use for doing that. Here's what it would look like with fetch, which uses AbortController:
useEffect(() => {
const finalUrl =`${apiUrl}id=${id}&timing=${time}&start=${finalStart}&end=${finalEnd}`;
// Create the controller so we can cancel the request
const controller = new AbortControlller();
// Pass `signal` to fetch vvvvvvvvvvvvvvvvvvvvvvvvvvv
fetch<DataType>(finalUrl, {signal: controller.signal})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
})
.then(setData)
.catch(error => {
console.log(error);
});
// Return a cleanup callback
return () => {
// Cancel the request since its response would be out of date
controller.abrt();
};
}, [time, finalStart, finalEnd]);
console.log(data);

React Native axios api call Shopify

Good morning guys, I try to fetch data from Shopify using this method. But it does not working.
Request failed with status code 400
May you share your little experience ?
I'm working on React Native Project.
const api_key = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://${api_key}:${password}#store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url:url
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});
It's most likely that the authentication is failing. Move the auth parameters to axios header. Try this
const username = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url,
auth: { username,password }
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});

Undefined 404 and React Hook useEffect has a missing dependency

I have a super cute site for flower-fans where you can find a profile of a flower (a mock api), read some info and put a note on each and every flower. Though, I'm not able to make the note stick anymore. So frustrating as it worked a while ago. I have updated the dependencies and also the settings for deploying on Netlify. In Postman I get the same message as in the console, which is not found 404.
I get a message in Terminal that the React Hook useEffect has a missing dependency (flowerId) too.
Down below you'll see the error message and here is a link to my deployed site:
https://flowerinspoapi.netlify.app/
Error message from Console
GET https://flowerinspoapi.netlify.app/flowers/undefined 404
Code from Flowerinfo.js
// Fetching the comments for the flowers
const url = "https://flowers-mock-data.firebaseio.com/comments/TheresaUlwahn"
export const FlowerInfo = () => {
const { flowerId } = useParams()
const [flower, setFlower] = useState([])
const [flowerMessages, setFlowerMessages] = useState([])
const [postedMessage, setPostedMessage] = useState("")
// Fetching the ID of the flowers
useEffect(() => {
fetch(`https://flowers-mock-data.firebaseio.com/flowers/${flowerId}.json`)
.then((res) => res.json())
.then((json) => {
setFlower(json)
})
}, [flowerId])
// Fetching the messages
useEffect(() => {
fetch(`https://flowers-mock-data.firebaseio.com/comments/TheresaUlwahn/${flowerId}.json`)
.then((res) => res.json())
.then((json) => {
console.log('All messages for the flower: ', json)
if (json !== null) {
setFlowerMessages(json)
}
})
}, [postedMessage])
const handleFormSubmit = (flowerId, message) => {
// console.log('POST THIS MESSAGE: ', message, 'FOR THE FLOWER: ', flowerId);
fetch(url + `/${flowerId}/.json`, {
method: "POST",
body: JSON.stringify({ message }),
headers: { "Content-Type": "application/json" }
})
.then(() => {
console.log('posted !')
// window.location.reload();
setPostedMessage(message)
})
.catch(err => console.log("error:", err))
}
var result = Object.keys(flowerMessages).map(function (key) {
return [key, flowerMessages[key]];
});

React Native AsyncStorage: Get Token and Use it in a refactored API fetch

I have decided to put all my API calls in a seperate file and they are all stateless.
const get = endPoint => {
let token = "c8c17003468314909737ae7eccd83d4b6eecb792"; //I have put this token here manually
return fetch(endPoint, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Token " + token
}
}).then(response => response.json());
};
and in the same file i have the actual API calls. Example is as follows.
export const loadGroups = () => {
const endPoint = "https://xxxx.com/api/groups/";
return get(endPoint);
};
This works perfectly when i call the API from various components as follows.
import { loadGroups } from "../../api";
componentDidMount() {
loadGroups()
.then(responseJson => {
this.setState({
groups: responseJson
});
})
.catch(error => {
console.error(error);
});
}
However, I want to use AsyncStorage to retrieve a stored token and the due nature of it is to return a promise. This works well when i write the functions of getting the token and storing it in SetState in every component that I do the calls. I really want to refactor the code and using redux is a pain for me.
so far, i have written a file to get the token and it returns a promise.
import { AsyncStorage, Text } from "react-native";
const MyToken = async () => {
try {
const retrievedItem = await AsyncStorage.getItem("userToken");
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
return null;
}
};
export default MyToken;
And in the API file, I have re-written the code above to
const get = endPoint => {
MyToken().then(token => {
console.log(token, "try 1"); //this works
const lookupOptions = {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Token " + token
}
};
return fetch(endPoint, lookupOptions).then(response => {
console.log(response.json(), "promise response,json");
response.json();
});
});
};
However, whenever i call loadGroups().then() (like in the first example) function in any component, I get an errors that loadGroups.then() can't be resolved
Is there any way to resolve this without state, redux, mobx keeping in mind i want my API code in stateless functions in seperate modules.
In V2 of get function, you are not returning any Promise. Either put a return statement in get function like
const get = endPoint => {
return MyToken().then(
...
);
}
Or return Promise explicitly from that function, consider following code snippets
const get = endPoint => {
return new Promise((resolve, reject) => {
MyToken().then(token => {
...
fetch(endPoint, lookupOptions)
.then(response => response.json())
.then(resolvedResponse => {
resolve(resolvedResponse);
}).catch(error => {
reject(error);
});
});
});
};
Hope this will help!

Resources