There is my problem: I want to show my github repos on a react componant but I've got the error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
There is my code:
import styles from "../styles/index.module.scss";
import { getRepos } from "../scripts/github";
export default async function Home() {
try {
const repos = await getRepos()
const hrefelement = repos.map(repo => <><p><a href={repo.homepage as string} target="_blank" rel="noopener noreferrer">{repo.name}</a></p></>)
return (
<div className={styles.container}>
<h1>diamant.dev</h1>
<div className={styles.repos}>
{hrefelement}
</div>
</div>
)
} catch (error) {
console.log(error);
return (
<div className={styles.container}>
<h1>diamant.dev</h1>
</div>
)
}
}
and the github.ts
file:
const githubUsername = 'diamantdev'
const githubUrl = `https://api.github.com/users/${githubUsername}/repos`
export const getRepos = async () => {
const response = await fetch(githubUrl);
const repos: [Repos] = await response.json();
const sortedRepos = repos.sort()
return sortedRepos.filter((repo) => repo.name != githubUsername || !repo.archived)
}
export default async function Home() {
Components cannot be async
. The standard approach for loading data is to have state for your data, which starts empty. You render once with that empty data (either rendering null or a placeholder), then fetch, then rerender once you have the data.
export default function Home() {
const [error, setError] = useState();
const [repos, setRepos] = useState();
useEffect(() => {
const fetch = async () => {
try {
const repos = await getRepos();
setRepos(repos);
} catch (err) {
setError(err);
}
}
fetch();
}, []);
if (error) {
return (
<div className={styles.container}>
<h1>diamant.dev</h1>
</div>
)
} else if (repos) {
return (
<div className={styles.container}>
<h1>diamant.dev</h1>
<div className={styles.repos}>
{hrefelement}
</div>
</div>
)
} else {
// still loading
return null
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.