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.
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
I am trying to render my firestore data to my web app using React.
here is my code
I can see the document ID when I console.log(posts.id), however I cannot find the content of that document.
Here are the content of a document
The method for getting the data is .data, as in:
console.log(posts[0].data())
To render something for each post might be something like:
<p>
{posts.map(doc => {
const data = doc.data();
return (
<div>{data.title}</div>
)
})}
</p>
Personally, unless i need something other than the data from the document, i tend to do my calls to .data() before i even put it into react state. That way i don't need to do it on each render. e.g:
useEffect(() => {
database.posts.get().then(snapshot => {
setPosts(snapshot.docs.map(doc => doc.data());
});
});
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.
I'm trying to learn redux, and so I'm creating a small site that uses a third party API to search and add movies to my own database, where I then use redux and react to display them. The point is to keep track of movie suggestions people give me, and when I watch them I remove them from the list.
I made this before in purely react, but I'm recreating it to learn redux.
The thing is, in my react-only version, I use this on a button click to delete and it works fine:
deleteThisMovie = () => {
this.props.closeModal();
this.props.toastAlert(`${this.props.title} successfully removed.`, 'success');
api.deleteMovie(this.props.id)
.then(this.props.updateMovies);
}
Here is the API code:
deleteMovie = (movieId) => (
superagent
.delete(`${API_HOST}/movies/${movieId}`)
.catch(err => console.error(err))
)
This deletes just fine.
=======================
In my react/redux version, this is my action:
function removeMovieFromDB(movieID) {
const request = superagent.delete(`${API_HOST}/movies/${movieID}`);
return request;
}
export function removeMovieAndRefresh(movieID) {
return dispatch => (
removeMovieFromDB(movieID).then((res) => {
dispatch(fetchMovies());
return res;
})
);
}
And in my component it's called like this:
<button type="button" onClick={() => this.removeMovie(apiID)}>
Remove
</button>
And that function is this:
removeMovie = (movieID) => {
this.props.removeMovieAndRefresh(movieID);
this.closeModal();
}
In this version, when I click the button, I get this error:
Failed to load {host_goes_here}/movies/12219: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 503.
My relevant server code is this:
const cors = require('cors');
app.use(cors());
and the mongoDB controller delete code:
moviesController.delete('/:id', (req, res) => {
Movie.findByIdAndRemove(req.params.id, function(err) {
if (err) throw err;
console.log('Movie removed successfully.');
})
.then(() => res.status(204).end());
});
Any idea what's going on with my redux delete? Am I missing something? I tried using axios as well but that didn't work. I also tried just a basic fetch with method: 'DELETE'. That didn't work either. But when I use my react only version with the same server, it deletes without issue.
I want to map all the issue titles for a repo and render them to li in a react component. I've been able to extract only the issue title using octokat library but unfortunately that library does not play nice with some other stuff i've got going on. Also, I'm sure i can do this with es6 and the fetch api.
Original Post:
Been having a hellava time finding info on using es6 fetch / promises with the github api. I'm trying to fetch issues for a repo but i'm obviously missing something... I've used a few different libraries to try and accomplish this but I'd like to just use fetch.
Update: Now my new goal is merely to console.log the titles... baby steps.
import React from "react";
export default class extends React.Component {
constructor() {
super()
this.state = {
issues: []
}
}
componentWillMount() {
// let issueArry = []
const url = "https://api.github.com/repos/fightplights/chode-stream/issues"
fetch(url)
.then(response => response) // i've tried with and without .json()
.then(body => console.log(body))
// this logs the same response
}
render() {
return (
<div>
<ul>
{here i will map this.state.issues (once i can get them =))}
</ul>
</div>
)
}
}
I know it's a simple error on my part. I'm still a fledgling. =)
...and obviously i need to render to the dom (not shown here)
#Andy_D is right that I wasn't parsing the body of the response, only the response itself (doh!) however now that i'm trying to data.map(issue => ...) I still get the error that data.map() is not a function. This leads me to believe that the data object is not the object the droids are looking for... hand waves in front of screen
Here's the response object in the first promise:
Response {
type: "cors",
url: "https://api.github.com/repos/fightp…",
redirected: false,
status: 200,
ok: true,
statusText: "OK",
headers: Headers,
bodyUsed: false
}
But when I take that response in the next
.then(data => console.log(data))
It is undefined...
I have tried returning the first response => response.json() (as andy suggested) but it's already json... am i wrong?
You need to read the JSON from the body of the response, what you are attempting to render is the full response body.
So:
fetch(url)
.then(response => response.json())
.then(data => data.map(...)
response.json() returns a promise, so you can .then it, the return value (data) will be the JS object/array you're looking for.
https://developer.mozilla.org/en-US/docs/Web/API/Body/json