I am working on react project. In my application In navigation bar I am displaying menu's. Here I want to display some text or message. This message has to be loaded from the API during the page load. Below is my code.
const NavigationBar = ({ className }) => (
<div className={className}>
<NavigationBarSection>
<NavigationTitle to="/">
<ReactSVG path={ipmLogoUrl} style={{ width: 24 }} />
</NavigationTitle>
<NavigationItem exact to="/">
Import
</NavigationItem>
<NavigationItem to="/timephase">Timephase</NavigationItem>
<NavigationItem to="/sync-progress">Sync Progress</NavigationItem>
<NavigationItem to="/parameters">Parameters</NavigationItem>
</NavigationBarSection>
<div>I want to display message from API</div>
<NavigationBarSection>
<Dropdown
label={
<BlockNavigationItem>
<Icon icon={<Help />} />
</BlockNavigationItem>
}
>
<DropdownItem
target="_blank"
href="/api/replenishment-parameters/keycode-parameters-template"
>
Download D&F Keycode Template
</DropdownItem>
<DropdownItem
target="_blank"
href="/api/replenishment-parameters/sims-keycode-parameters-template"
>
Download SIMS Keycode Template
</DropdownItem>
<DropdownItem
target="_blank"
href="/api/replenishment-parameters/timephase-template"
>
Download Timephase Template
</DropdownItem>
<DropdownItem
rel="noopener noreferrer"
target="_blank"
href="https://kmartonline.atlassian.net/wiki/x/5ICICg"
>
Help and Support
</DropdownItem>
</Dropdown>
<UserProfile />
</NavigationBarSection>
</div>
);
Can someone help me to complete this? Any help would be appropriated. Thanks
I have created a project using axios and reactjs , please check on GITHUB
Snippet from the project:-
GET CALL
axios.get('/posts')
.then(response => {
const posts = response.data.splice(0, 4);
const updatedPosts = posts.map(post => {
return{
...post,
author: 'Max'
}
});
this.setState({posts: updatedPosts});
})
.catch(error => {
console.log(error);
// this.setState({error: true});
})
POST CALL
let data = {
title: this.state.title,
body: this.state.body,
author: this.state.author
}
axios.post('/posts', data)
.then(response => {
// console.log(response)
// this.props.history.push('/posts');
this.props.history.replace('/posts');
// this.setState({submitted: true});
})
For your question, Axios the default standard. Node.JS also has a built-in request handler called Fetch API and you can read more about it here.
How each one works:
Fetch API:
Axios:
Differences:
1. With axios you automatically get a JSON Object.
If you wanted a JSON response when calling with Fetch, you would need to pass it to .json() first:
fetch('https://api.punkapi.com/v2/beers/1')
.then(response => response.json())
.then(data => console.log(data));
Axios already does that for you.
2. Axios does a better job handling errors:
Let's say you called the fetch API with a wrong URL:
The request returned a 400 error, but Fetch API still logged the data.
Now let's try axios:
This is way better! I get the error I was expecting and I didn't get the empty data back.
3. Monitoring POST requests:
Axios allows you to monitor POST requests:
Let's say that you sent a request but it is taking too much. With Fetch you won't know if it is just slow or if your code is broken. Axios allows you to monitor your requests.
axios.post('https://api.punkapi.com/v2/beers/1', data, {
onUploadProgress: ({ total, loaded }) => {
// Update progress
},
});
Axios with React Components:
Here is a great tutorial on the subject: Using Axios with React.
Basically, you define a function inside your component, which uses Axios and then you call it wherever you need that functionality. For a GET request it would be most suitable to call axios.get() in componentDidMount(). For other requests, you would define a separate function.
Summary:
There are many other aspects of Axios and its advantages over Fetch and there are also other packages similar to Axios. You might want to install it and play around with it.
You can use react-fetch-hook for this. Like this:
const NavigationBar = ({ className }) => {
const {data: message} = useFetch("<api_url_for_message>");
return <div className={className}>
...
<div>{message}</div>
...
</div>
}
React 16.8.0 is needed.
Related
I have a React Frontend and Django Backend. In my frontend I want to include a view for the PDF obtained by the backend. I tried using iframe and object HTML Tags, but they failed due to the missing authentication. My suggested approach would be requesting the PDF with axios.get, since this automatically handles the authentication. However, I could not find out how to handle the obtained PDF in case of temporarily storing and displaying it with react.
Currently my function is able to obtain the PDF and display it in a new window but I want to include it as an element within the current page.
const getPDF = () => {
axios
.get(
`${process.env.REACT_APP_API}/Link/to/the/PDF/`,
{
responseType: "blob",
}
)
.then((r) => {
window.open(URL.createObjectURL(r.data));
});
};
#react-pdf/renderer is used to render pdf from your page/application and is not made to render already made pdfs
You can use react-pdf to do what you want. It works great and lets you style your component the way you want.
In the content of the page I put the following:
<iframe src="" width={600} height={600} />
And I adapted the function to fill the iframe:
const getPDF = () => {
console.log("getPDF");
axios
.get(`${process.env.REACT_APP_API}/Link/to/the/PDF/`, {
responseType: "blob",
})
.then((r) => {
console.log(r.data);
const file = window.URL.createObjectURL(r.data
);
const iframe = document.querySelector("iframe");
if (iframe?.src) iframe.src = file;
})
.catch((err: AxiosError) => {
console.log(err);
});
};
So you have half the work done! in the other half, maybe an option is to look at this component:
#react-pdf/renderer
I used this package without any complaints.
** Sorry for redirecting to the wrong library. I use this instead:
pdf-viewer-reactjs
this my cart Icon which is a separate cart component
<IconButton aria-label="cart">
<StyledBadge badgeContent={localStorage.getItem('count')}
color="primary">
<ShoppingCartIcon style={IconStyling.styleListShopIcon} />
</StyledBadge>
</IconButton>
This is mine code to update localStorage while posting new cart item
axios.post(`http://localhost:5000/cart`, CartData)
.then((result) => {
localStorage.setItem('count', result.data.length);
}).catch((error) => {
console.log(error)
})
React uses references to check if something changed in order to trigger updates.
By using localStorage the reference would be always the same and it won't trigger updates.
A "hacky" way to basically keep everything you have is something like this:
Add a state to the component you want to render and a forceRender function:
const [render, setRender] = React.useState(0)
function forceRender(){
setRender(render + 1)
}
Then add forceRender to your Axios fetch:
axios.post(`http://localhost:5000/cart`, CartData)
.then((result) => {
localStorage.setItem('count', result.data.length);
forceRender();
}).catch((error) => {
console.log(error)
})
Beware that this would be you literally telling react when to rerender and there are better ways to do this builtin...
I'm new to react. I have a problem with url.
I get data from Github API through fetch request. Now I have to show only URL from API data but it shows me project url and data url mixed.
Here's the code which will simplify the problem.
fetch(
`https://api.github.com/users/${username}/repos?per_page=${count}&sort=${sort}&client_id=${clientId}&client_secret=${clientSecret}`
)
.then((res) => res.json())
.then((data) => {
this.setState({ repos: data });
})
.catch((err) => console.log(err));
this will update state with result data.
Here I destructured it from state.
const { repos } = this.state;
<Link to={repo.html_url} className="text-info" target="_blank">
{repo.name}
</Link>
now I mapped repos and return JSX and show html_url from data. But the problem I'm facing is not showing url from data.
It shows like this
<a class="text-info" target="_blank" href="**/profile/**https://github.com/ahsandani001/amazon-clone">amazon-clone</a>
I copy this from chrome devtools. ("/profile/" is extra).
How can I remove this. Where am I mistaken?
Somebody help. Thanks in advance.
I have this button inside a react component, and I call the fetchImages function with it
<button onClick={() => this.fetchImages()}
type="submit" className="btn btn-primary mt-4">
Mais Imagens
</button>
FetchImages is a function where I use axios to make a get request on a FLASK API, to get all the itens in one page
fetchImages(page) {
const { filters } = this.state;
this.setState({ loadingFetchImages: true });
const { headers } = getAxiosConfig();
axios.get(`${API_URL}/api/imagens_selecionadas`, { params: { page, q:
filters }, headers })
.then((response) => {
const images = response.data.objects.map(image => ({ ...image, check:
false }));
this.setState({ images, loadingFetchImages: false });
})
.catch(handleRequestError);
}
I need to found a way to, everytime the user click the button, the page advance with the parameter ?page=1, ?page=2, etc. So i need to call http://localhost:5000/api/imagens_selecionadas?page=1, ?page=2 and etc...
I cant found a way to do that, can someone help me?
you can define a store for your component and save your variable and constant inside it. if you pass your store via your component, you always have every critical and necessary variable you want
I'm completely new to React and having a hard time understanding it.
I've been tasked with creating a really simple API fetch to an OData endpoint.
Now, I've come across this library https://www.npmjs.com/package/react-odata
Which looks fantastic! However I just do not understand how to even get something like this working.
I understand the very basic principles of how react works and have gone through many basic tutorials. But for whatever reason I can not get my head around this one.
So how could I use this library to simply query an OData endpoint and display the raw data?
So the issue with this, is that I didn't understand that I still have to explicitly make the call and return the data from that.
import React, { Component } from 'react';
import Fetch from 'react-fetch-component';
import OData from 'react-odata';
const baseUrl = 'http://services.odata.org/V4/TripPinService/People';
const query = { filter: { FirstName: 'Russell' } };
export default class App extends Component {
render() {
return (
<div>
<h1>Basic</h1>
<OData baseUrl={baseUrl} query={query}>
{({ loading, data, error }) => (
<div>
{loading && <span>Loading... (()=>{console.log(loading)}) </span>}
{data && data.value.map((d, i) => <div key={i} id={i}>{d.FirstName}</div>)}
</div>
)}
</OData>
</div>
);
}
/* Setup consistent fetch responses */
componentWillMount() {
fetch('http://services.odata.org/V4/TripPinService/People')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.value[0].FirstName
})
.catch((error) => {console.error(error)});
}
}
from the given link in the question I found that this component used the react-fetch-component as a base to make the call.
It seems that the package you linked would expose a React component that you would use to wrap your own components so you would have access to the fetched data and could pass it down as properties. At least that is what I understand from its README.
I imagine it would be something like this:
<OData baseUrl={baseUrl} query={query}>
{ ({ loading, error, data }) => (
<div>
<YourComponent data={data} />
</div>
)}
</OData>
This would be using react-odata, but you don't need that package to do what you want. You could just do a regular AJAX call on the URL and feed your components with the returned data.
This post may help: http://andrewhfarmer.com/react-ajax-best-practices/