I've got a list of names fetch from a external API called SWAPI and I would like to get a single detail character. I'got to connect the data and the list is working perfectly but when I click and sends me to the single detail character, doesn't recognise which character id, it says undefined. I can get the page with the character but not with the corresponding id.
<ul>
{data.results.map((result) => (
<div key={result.episode_id} className="column">
<Link
href={`/character/?id=http://${result.id}`}
>
<h4 className="card-title">
<a>{result.name}</a>
</h4>
</Link>
</div>
))}
</ul>
export async function getServerSideProps() {
const res = await fetch(`https://swapi.dev/api/people/`)
const data = await res.json()
return { props : {data} }
}
I tried to route as a Link with href to send me to the single character with the ${result.id} to fetch only the id but it doesn't like the solution.
It sends me to the page character but doesn't recognise the id, it says undefined.
Related
I had some alert components when each clicked; it will get redirected to a page
<div className="question11">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: "/[itm]",
query: { id: itm._id },
}}
as={`/${encodeURIComponent(
itm.Name.replace(/[^a-zA-Z0-9 - _ . ~]/g, "").replace(
/ /g,
"-"
)
)}`}
>
<Alert className="question13">{itm.Name}</Alert>
</Link>
))}
</div>
The redirected page has a URL in the following pattern
http://localhost:3000/itm.Name. Example: http://localhost:3000/spiderman-no-way-home-release-date-in-india. I am passing itm._id for accessing the corresponding data on the redirected page
export async function getServerSideProps(context) {
var id1 = context.query.id;
// console.log(context.query.id);
const queryRequest = fetch("https://askover.wixten.com/questone/" + id1).then(
async (res) => await res.json()
);
When I click on alert components, I can pass the itm._id, and the page is redirected properly. The issue occurs when I manually enter the URL in the browser.The issue here is not getting the itm._id from the alert component. The answer that I came up with here is to create an API to access the API by passing the itm.Name, but that will require deconstructing the itm.Name to its original form, and itm.Name might not be unique every time is there another method by which I can access itm._id itself also, if I can use the URL in http://localhost:3000/itm._id/itm.Name
this format also, I think it will be okay just as StackOverflow does it.
When you refresh the page you will lose the context, even if you use some store(local, session, etc) that will not work for the user visiting your app for the first time.
One thing always remains is URL, neither storage nor context.
To solve this kind of issue, what you can do is pass the id and slug parameters to the URL and read whenever requires.
Check more details here
Next.js Directory
pages
index.js
[id]
[slug].js
The URL will look something like this: https://localhost:3000/123/my-post-slug
, Slug is optional, It'll help for SEO purposes.
[slug].js
const Component = (props) => (
<div>
<h1>{props.title}</h1>
<p>{props.content}</p>
</div>
);
export async function getServerSideProps(context) {
const id = context.params.id;
const data = fetch(`https://askover.wixten.com/questone/${id}`).then((res) => await res.json());
return {
props: data,
}
}
I'm building a simple React app for a class project using the National Weather Service API. The idea is: get an API return for a set of latitude and longitude coordinates (which I'll expand later so that users can input their address and a separate geocoding API can return their lat/long coordinates), which contains the URL to the forecast data (using grid coordinates), use that URL to get a second API return (believe it or not this is how NWS says it should be done) which is an object which contains a nested object properties that contains a nested array periods of objects that each represent a day/night forecast, each identified with a name and number.
I have the following code successfully displaying a list of the period names (to start), but I am getting an error in console: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0.
Internet searches (including stackoverflow) tell me this occurs because the return isn't in JSON format, but all the resources I can find on the NWS API says it returns JSON. If it didn't; I don't think I'd get anything displaying on the web page (right?), so I must be getting JSON back since I'm seeing the period names.
In addition, the names only display when I update the browser that's displaying my live server. If I refresh the page it disappears. What's going on?
import React, { useState, useEffect } from 'react'
function GetForecast() {
const [gridEndpoint, setGridEndpoint] = useState('');
const [forecastArray, setForecastArray] = useState([]);
useEffect(() => {
fetch(`https://api.weather.gov/points/45.5312,-122.6447`)
.then(reply => reply.json())
.then(json => json.properties.forecast)
.then(link => setGridEndpoint(link))
.then(
fetch(`${gridEndpoint}`)
.then(reply => reply.json())
.then(json => json.properties.periods)
.then(array => setForecastArray(array))
)
}, [])
return (
<div>
{forecastArray.map((period, index) => (
<div key={index}>{period.name}
</div>
))}
</div>
)
}
Had someone point out to me that setGridEndpoint() isn't updating gridEndpoint the way I had it written. Here's what I replaced it with.
useEffect(() => {
fetch(`https://api.weather.gov/points/45.5312,-122.6447`)
.then(reply => reply.json())
.then(json => json.properties.forecast)
.then(link => fetch(link))
.then(reply => reply.json())
.then(json => json.properties.periods)
.then(array => setForecastArray(array))
}, [])
I read the docs of dynamic routes but they didn't explain much about how dynamic routes will work with "catching all routes".
My folder structure for this route is:
└──pages
└──catalog
└──[[...slug]].js
Here's my code:
export default function Catalog(props) {
return (
<Product product={props.product} />
)
}
export async function getStaticProps({ params }) {
const productSlug = params.slug[params.slug.length-1];
const data = await getSingleProduct(productSlug)
return {
props: {
product: data.product,
},
revalidate: 30
}
}
My API is WP and I have product pages URI like this /catalog/category/sub-category/product/
So if I go to the URL /catalog/category/sub-category/product/ it works fine with the code I shared below because I have const productSlug = params.slug[params.slug.length-1]; which will get my slug which I can pass to the API and use the product data just fine.
But I want to work with categories too, so if I go to /catalog/category/sub-category/ it should load the category page, and if I go to /catalog/category/ it should load up that category page.
Even this will work with the code I have because I'm getting the last element of params array which is the product slug, but that's NOT always the case. Sometimes the product is without any sub-category so the URI would be /catalog/category/product which means I can't fix it to the third element of the array and use the other two as category slugs.
The params gives me an array without any key or anything and I can't seem to figure out how to achieve this in next.js
Any help is appreciated!
Im working on a project trying to fetch a name of the current user that is logged in.
When we create a user its getting added in the database with a unique id as row name.
Here you can see all the users that are registered but i only want the one that is logged in so i can pick the first and last name to say "Hello (bla) (bla)"
The code i have now it this :
import React from "react"
import { auth, database } from '../../handlers/Firebase'
export default function Dashboard() {
const user = auth.currentUser
const refUserInformation = database.ref('UserInformation/')
refUserInformation.on('value', function(data){
console.log(data.val())
})
return (
<div className="page-dashboard">
<div className="maxtext">
<p>userid: {user.uid}</p>
<p>Naam: </p>
</div>
</div>
)
}
Can just someone help me out with fetching the logged in user (so not a loop)
In summary, the problem is that I currently get all users back in my console log, but I only need the one that is logged in and on the appropriate dashboard. I would like to post this name (not with a loop but a single request)
To get just the user with a given user_id value, you will have to use a query:
const refUserInformation = database.ref('UserInformation/')
const currentUserQuery = refUserInformation.orderByChild('user_id').equalTo(user.uid);
currentUserQuery.on('value', function(snapshot){
snapshot.forEach((data) => {
console.log(data.val())
});
})
In general, I'd recommend storing user information with the UID as the key. That way:
Each UID can by definition occur only once in the database, since keys are unique under a parent node.
Looking up the user info by their UID becomes simpler, since you won't need a query.
To store the user under their UID use refUserInformation.child(user.uid).set(...) instead of refUserInformation.push(..).
I try to get from a list of users to only one user and display his profile on another page.
I want to do so with the routerLink and passing on an id of this specific user to the next page.
The routing is working, Im directed to the profile page but when I log the results of the http request I still get back the whole list of users like in the users page instead of the details of one user.
I have tried many things like changing the path of the url in my user.service.ts but that didn't solve the problem I even got 404 request errors when using this path ${this.url}/users/${id}/ instead of ${this.url}/users/?i=${id}/ (where its working).
The api docs is saying though that in order to retrieve one single user its http://1234//users/{id}/ it this scheme while id is an integer. But when I want to apply that scheme I get the 404 error.
Thats why I have to use the ?I= version but there the problem is I only get the full list of users on the next page.
MY CODE:
user.service.ts
// get a user's profile
getUserDetails(id): Observable<any> {
return this.http.get(`${this.url}/users/?i=${id}/`); // why add ?i
}
user.page.ts
// get all users in the users page
getAllUsers() {
this.userList = this.userService.getList()
.pipe(map(response => response.results));
}
user.page.html
<ion-avatar class="user-image" slot="start" [routerLink]="['/','profile', 'user.id']">
<ion-img src="assets/22.jpeg"> </ion-img>
</ion-avatar>
profile.page.ts
information = null;
...
ngOnInit() {
// Get the ID that was passed with the URL
let id = this.activatedRoute.snapshot.paramMap.get('id');
// Get the information from the API
this.userService.getUserDetails(id).subscribe(result => {
this.information = result;
console.log(result);
});
}
It seems like the url is wrong. If it was me I would console.log the url and compare it to the docs. Heres a snippet to try a few variations:
const id = 1;
const options = [
`${this.url}/users/?i=${id}/`,
`${this.url}/users/?i=${id}`,
`${this.url}/users/i/${id}/`,
`${this.url}/users/i/${id}`,
`${this.url}/user/?i=${id}/`,
`${this.url}/user/?i=${id}`,
`${this.url}/user/i/${id}/`,
`${this.url}/user/i/${id}`,
];
for (const option of options) {
try {
const response = await this.http.get(option);
console.log(options, response);
} catch (e) {
}
}
I would also consider dropping the second http request. If the first request returns all the required data you could just store it in a variable on the service.