I keep getting this error when attempting to update a component with new data fetched from a server.
Description:
Portfolio.js
I have an app that has a portfolio where the projects of the site are shown. When you click an item in portfolio, you are redirected (with react-router) to the individual project.
Project.js
The project component uses the fetch api to retrieve data from a server. Which works perfectly because when the url specifies the project to be show like: /portfolio/project/:id, and based on the id received the data is fetched and displayed correctly.
The data retrieved
What is retrieved trough fetch api is just the result of a AJAX POST request to a server with the only parameter of the project id, which only returns the info of the project. (name, description, images, and other ones not much important)
The issue:
As far I've analyzed the application to see when this error is triggered, I found that this warning comes out when the amount of images for the new project loaded is smaller than the amount of images of the project already rendered.
An example:
We are inside a project. The url is portfolio/project/1 and the server data returned that this project has 5 images. They are loaded and you can view the project correctly.
Now, we use the menu to react-router-redirect to portfolio/project/2 and the server returned data with 7 images. They are loaded and the project data as well to view the project.
So, let say that we choose the option in the menu to view the project portfolio/project/3 which has 3 images, and then the warning comes up.
Browser:
Console log:
The code:
Since the error says the problem is inside Project.js, I am only adding this code so the question doesn't look overloaded and full of weird code.
Project.js
import React,{Component} from 'react'
import Footer from '../Footer/Footer'
import Header from '../Header'
import SubNav from '../SubNav'
import Details from './Details'
import {Link} from 'react-router-dom'
import {Configurations} from '../AppConfig'
class Project extends Component{
state = {
projectInfo: null,
reloadHandlerActive: false,
projectID : this.props.match.params.id,
projectName: "",
topProjectInfo: [],
images: []
}
createImages = (project) =>{
let Images = Object.values(project.images),
ImagesURI = Images.map((img, index)=>{
if( img.includes('Desarrollos.jpg') || img.includes('Home.jpg') || img.includes('H.jpg') ){
return null
}
return project.path+img
})
ImagesURI = ImagesURI.filter(function (e) { //Clear null values
return e != null;
})
return ImagesURI
}
reloadHandler = (id) =>{
const {createImages} = this
fetch(Configurations.API.projectInfo(id))
.then((result)=>{return result.json() })
.then((project)=>{
if(project === "error"){
alert("Error")
}else{
this.setState({
projectInfo: project,
images: createImages(project)
},function(){
document.getElementsByClassName("nav-button")[0].click()
})
}
})
}
componentWillMount(){
const {createImages} = this
fetch(Configurations.API.projectInfo(this.state.projectID))
.then((result)=>{return result.json() })
.then((project)=>{
if(project === "error"){
alert("Error")
}else{
this.setState({
projectInfo: project,
images: createImages(project)
},function(){
window.initDogma()
})
}
})
}
componentDidMount(){
window.onload = window.initShit()
}
render(){
const {projectInfo,images} = this.state
console.log(projectInfo)
if(!projectInfo){
return(<h1>. . .</h1>)
}
return(
<div >
<Header />
<SubNav reloadHandler={this.reloadHandler} />
<div className="content full-height no-padding">
<div className="fixed-info-container">
<Link to="/portfolio"><button className="goBackBtn">Desarrollos</button></Link>
<h3>{projectInfo.project.project}</h3>
<div className="separator" />
<div className="clearfix" />
<p>
{projectInfo.project.address}
</p>
<span className="project-status">{projectInfo.project.status}</span>
<h4>CaracterÃsticas</h4>
<Details price={projectInfo.project.price} features={projectInfo.project.features} />
<Link className=" btn anim-button trans-btn transition fl-l" to={"/contact/?project="+projectInfo.id}>
<span>Informes</span>
<i className="fa fa-eye" />
</Link>
</div>
{/* fixed-info-container end*/}
{/* resize-carousel-holder*/}
<div className="resize-carousel-holder vis-info gallery-horizontal-holder">
{/* gallery_horizontal*/}
<div
id="gallery_horizontal"
className="gallery_horizontal owl_carousel"
>
{
images.map((img,index)=>{
return (
<div key={index}className="horizontal_item">
<div className="zoomimage">
<img src={img} className="intense" alt="" />
<i className="fa fa-expand" />
</div>
<img src={img} alt="" />
<div className="show-info">
<span>Info</span>
<div className="tooltip-info">
<h5>Imagen de muestra</h5>
<p>
Imagen del desarrollo
</p>
</div>
</div>
</div>
)
})
}
</div>
{/* resize-carousel-holder*/}
{/* navigation */}
<div className="customNavigation">
<a href="/" className="prev-slide transition">
<i className="fa fa-angle-left" />
</a>
<a href="/" className="next-slide transition">
<i className="fa fa-angle-right" />
</a>
</div>
{/* navigation end*/}
</div>
{/* gallery_horizontal end*/}
</div>
<Footer />
</div>
)
}
}
export default Project
I'm currently looking how to fix this, but if someone could give me an advice or the origin of the issue would be really helpful.
By the time your question was posted, there was an issue open at reactjs github repo talking about something similar. It is now solved, but you may want to read the article.
Related
I have a file called Data.js where i've exported a list with some objects as below
export const DATA = [
{
'loc':'WEB',
'title':"Bukkit List",
'img':'/img/Projects/Bukkit-List.PNG',
'desc':"Bukkit-List is a easy to use and free task managing webapp, with password protection now!",
'fullDesc':""
},
{
'loc':'WEB',
'title':"SilenxIka-Github",
'img':'/img/Projects/SilenxIkaGithub.PNG',
'desc':"First github website for Project SilenxIka, which is completly made from vanilla HTML/CSS/JS",
'fullDesc':""
}
]
Now i have a page called projects.js where i've imported this list and displayed it's content in HTML as below
import Image from 'next/image';
import Link from 'next/link'
import { DATA } from '../../components/Data'
const WEB_RELATED = []
const PC_EXES = []
for(let i=0;i<DATA.length; i++){
if(DATA[i]['loc'] == 'WEB'){
WEB_RELATED.push(DATA[i])
}
else if(DATA[i]['loc'] == 'EXE'){
PC_EXES.push(DATA[i])
}
}
const WEB = WEB_RELATED.map(item =>
<div className="PROJECTS_Projects">
<div className="PROJECTS_Projects_Image">
<Image
className='PROJECTS_Projects_image'
src={item['img']}
layout='fill'
// objectFit='contain'
/>
</div>
{/* if someone clicks on this link i want them to go to [project].js and send This item to [projcet].js */}
// Link-2
<Link href={'/projects/' + WEB_RELATED.indexOf(item)}>
<a>{item['title']}</a>
</Link>
<p>{item['desc']}</p>
</div>
);
const PC = PC_EXES.map(item =>
<div className="PROJECTS_Projects">
<div className="PROJECTS_Projects_Image">
<Image
className='PROJECTS_Projects_image'
src={item['img']}
layout='fill'
// objectFit='contain'
/>
</div>
{/* if someone clicks on this link i want them to go to [project].js and send This item to [projcet].js */}
// LINK -1
<Link href={'/projects/' + PC_EXES.indexOf(item)}>
<a>{item['title']}</a>
</Link>
<p>{item['desc']}</p>
</div>
);
export default function index() {
return (
<div className="PROJECTS_Container">
<div className="PROJECTS_Sub_Container">
<div className="PROJECTS_New">
<h1>Web-Related</h1>
<div className="PROJECTS_Present">
{WEB}
</div>
</div>
<div className="PROJECTS_New">
<h1>Pc apllications</h1>
<div className="PROJECTS_Present">
{PC}
</div>
</div>
</div>
</div>
)
}
then i have a link in this page with link /projectsDisplay/{index_of_item_in_Data.js_List} which then leads to the page below
This projectDisplay.js file is covered in [] so it has the router.query thingie
export default function title({project}) {
return (
<div className='DISPLAY_Container'>
<div className="DISPLAY_Sub_Container">
<div className="DISPLAY_Image">
<Image
// src={`'/${img}'`}
src={'/img/Projects/Cluq.PNG'}
// src={data['img']}
layout='fill'
/>
</div>
<div className="DISPLAY_Info">
<h3>Here also</h3>
SUS
<p>Want data here</p>
</div>
</div>
</div>
)
}
I wanna display the same data the user clicked for in the first page, in simple words the item in the first page shall be accessible here in the last page's HTML
So I'm attempting to redo a personal blog site that I built entirely in Django with the template system with a DRF / Next.js set up. The problem is that I can display the blog posts on the page no problem with and unpaginated django serializer. When I paginate the django serializer because I only want a few posts on the from page I get the error
TypeError: p.map is not a function
Here is the code that works:
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import React, { Component } from 'react'
import Header from '../components/header'
import Link from 'next/link';
function Home({ p }) {
return (
<React.Fragment>
<Header />
<header className="masthead">
<div className="container position-relative px-4 px-lg-5">
<div className="row gx-4 gx-lg-5 justify-content-center">
<div className="col-md-10 col-lg-8 col-xl-7">
<div className="site-heading">
<h1>test</h1>
<span className="subheading">Test subheading</span>
</div>
</div>
</div>
</div>
</header>
{p.map((post) => (
<div className="container px-4 px-lg-5" key={post.id}>
<div className="row gx-4 gx-lg-5 justify-content-center">
<div className="col-md-10 col-lg-8 col-xl-7">
<div className="post-preview">
<Link href={`/posts/${encodeURIComponent(post.slug)}`}>
<a><h2 className="post-title">{ post.title }</h2>
<h3 className="post-subtitle">{ post.article_body.substr(0,50)}</h3></a>
</Link>
<p className="post-meta">
Posted by { post.author } in { post.article_type }
on { post.date_posted }
</p>
</div>
</div>
</div>
</div>
))}
<div className='container'>
<hr className="my-4" />
<div className="d-flex justify-content-end mb-4"><a className="btn btn-primary text-uppercase" href="/allposts">All Posts →</a></div>
</div>
</React.Fragment>
)
}
export async function getStaticProps() {
const res = await fetch("https://www.api.com/api");
const p = await res.json();
console.log
return{
props: {
p
},
};
};
export default Home;
This code displays all blog entries that are in the database and works just fine.
As soon as I change the api address to the paginated version I get the error:
TypeError: p.map is not a function
This api is being paginated by Django Rest Framework serializer.
If anyone could help me here it would be great. I've been banging my head against the wall for the last two days trying to figure this out.
At first check does your api returns an array? if it says map is not a function that's for sure that p is not an array
Can anyone explain what's going on here?
On the index page referenced below there is a section where I source data from a WordPress API to generate the four most recent posts from a client. When running in develop mode with Gatsby, the website is presented fine, but when I upload the website to Netlify and build it out, the data disappears and leaves nothing more than an empty set of p tags.
When I go into development tools and step through breakpoints, I notice that the data in question appears on the website, but then disappears once the webpack fires and the modules are bundled. It's almost as if this data is getting overwritten. When I navigate away from this page on the same website, and then return, the p tags HAVE the data in question. I'm assuming the webpack overwrites the initial code, and then when I come back to the page the webpack has already fired so it loads the information fine? How do I work around this? Excuse me if this is a silly/obvious question.
Full code in reference:
import React from "react"
import { Link, graphql, useStaticQuery } from 'gatsby'
import Layout from '../components/layout'
import indexStyles from '../components/modules/index.module.css'
import Carousel from 'nuka-carousel'
import header1 from '../img/header1.jpg'
import header2 from '../img/header2.jpg'
import header3 from '../img/header3.jpg'
const IndexPage = () => {
const data = useStaticQuery(graphql`
query {
allWordpressPost (sort: {fields:date, order:DESC}) {
edges {
node {
title
slug
excerpt
date(formatString:"MMMM DD, YYYY")
}
}
}
}
`)
return (
<Layout>
<div className={indexStyles.indexCarousel_container}>
<Carousel
autoplay={true}
autoplayInterval={5000}
pauseOnHover={false}
wrapAround={true}
renderCenterLeftControls={({ previousSlide }) => (
<button onClick={previousSlide} className={indexStyles.indexCarousel_button}><i className="fas fa-arrow-left"></i></button>
)}
renderCenterRightControls={({ nextSlide }) => (
<button onClick={nextSlide} className={indexStyles.indexCarousel_button}><i className="fas fa-arrow-right"></i></button>
)}>
<div className={indexStyles.indexCarousel_slideContainer}>
<img src={header1} alt="Pencil case with cat, heart, and cupcake design."></img>
<div>
<h2>Shop</h2>
</div>
</div>
<div className={indexStyles.indexCarousel_slideContainer}>
<Link to="/blog"><img src={header2} alt="Notepad next to a cup of coffee."></img></Link>
<div>
<h2>Blog</h2>
</div>
</div>
<div className={indexStyles.indexCarousel_slideContainer}>
<img src={header3} alt="Colorful pencil cases."></img>
<div>
<h2>Cute Castle VIP</h2>
<p>Save 20%!</p>
</div>
</div>
</Carousel>
</div>
<h1 className={indexStyles.indexHeader}>Latest Posts</h1>
<div className={indexStyles.indexPost_container}>
<div className={indexStyles.indexPost_container}>
{data.allWordpressPost.edges.map((edge, i) => {
if (i < 4) {
return (
<div className={indexStyles.index_post}>
<h2><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_title} dangerouslySetInnerHTML={{ __html: edge.node.title }}></Link></h2>
<p className={indexStyles.post_date}>{edge.node.date}</p>
<p className={indexStyles.post_excerpt} dangerouslySetInnerHTML={{ __html: edge.node.excerpt }} />
<p><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_link}>Read more</Link></p>
</div>
)
}
})}
</div>
</div>
</Layout >
)
}
export default IndexPage
The section of code that disappears and reappears:
<div className={indexStyles.indexPost_container}>
<div className={indexStyles.indexPost_container}>
{data.allWordpressPost.edges.map((edge, i) => {
if (i < 4) {
return (
<div className={indexStyles.index_post}>
<h2><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_title} dangerouslySetInnerHTML={{ __html: edge.node.title }}></Link></h2>
<p className={indexStyles.post_date}>{edge.node.date}</p>
<p className={indexStyles.post_excerpt} dangerouslySetInnerHTML={{ __html: edge.node.excerpt }} />
<p><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_link}>Read more</Link></p>
</div>
)
}
})}
</div>
</div>
A link to the Netlify project.
https://zealous-engelbart-509321.netlify.com/
Thanks in advance for your help!
I have created a basic React project that is pulling data from a SQL server. I would like this to be able to be rendered conditionally depending on what button has been clicked.
This is my Display Users Component which is used within my AdminViewUsers component (What is actually displaying the users).
import React, { Component } from 'react';
import './customers.css';
class DisplayUsers extends React.Component{
constructor(){
super();
this.state= { users: [] }
}
componentDidMount(){
this.setState({
users: this.getItems()
})
}
getItems(){
fetch('/admin-view-users')
.then(recordset => recordset.json())
.then(results => { console.log(results.recordset); this.setState({'users': results.recordset}); });
}
render () {
console.log(this.state.users)
return (
<ul>
{this.state.users && this.state.users.map(function(user, index){
//if (user.severity === 1){
return(
<div className ="jumbotron">
<li>
Severity: {user.severity}
</li>
<li>
<p>User Name:{user.name} </p>
</li>
<li>
User Email: {user.email}
</li>
<li>
Description of Issue: {user.description}
</li>
<button>See Details</button>
</div>
)
})
}
</ul>
);
}
}
export default DisplayUsers;
This is my AdminViewUsers Component
import logo from '../codestone logo.png';
import {Link } from 'react-router-dom'
import '../bootstrap.min.css'
import '../bootstrap.min.css'
import '../App.css'
import Customers from "../Components/customers";
import DisplayUsers from "../Components/DisplayUsers";
import { ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem, DropDownButton } from 'reactstrap';
function Home() {
return (
<div>
<Header/>
<SeveritySelector/>
<DisplayUsers/>
</div>
);
}
function Header(){
return (
<div class="jumbotron">
<div className = "User-Menu">
<Link>User details </Link>
</div>
<img className='profile-image' alt='icon' src={logo} width="340" height="60"/>
<Navigation/>
</div>
)
}
function Navigation (){
return(
<div>
<br/>
<div class="btn-group">
<Link to= '/home'><button type="button" class="btn btn-light">Home</button></Link>
<Link to= '/admin-view-users'><button type="button" class="btn btn-light">View Users(Admin)</button></Link>
</div>
</div>
)
}
function SeveritySelector (){
return(
<div className = "Severity-Toolbar">
<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group mr-2" role="group" aria-label="First group">
<button type="button" class="btn btn-secondary">Severity High</button>
<button type="button" class="btn btn-secondary">Severity Medium</button>
<button type="button" class="btn btn-secondary">Completed</button>
<button type="button" class="btn btn-secondary">View All</button>
</div>
</div>
</div>
)
}
export default Home;
Essentially I would like to use the function Severity Selector to be the decider of how the statement is displayed.E.g If the high severity button is selected then it will display all with a high severity (1) if medium selected all with medium severity (2) and completed to have a severity of 3. Finally a button to display all.
What in your opinion is the best way to do this? I understand I could use multiple statements within my "server.js" and load different queries and have them connected to different pages.
But is there a way that I could just use a if statement or something similar to determine what button is selected to avoid multiple transactions with the server? You can see a brief attempt I had within the display users with an if statement which worked but just was not dependent on the buttons.
Conditional render can be achieved using various techniques, the most used is the bracket style variant. It can be used in the following way:
function Header(){
const showFirst = true;
return (
<div class="jumbotron">
{showFirst && <MyFirstComponent />}
{!showFirst && <MySecondComponent />}
</div>
)
}
This will render the <MyFirstComponent /> if showFirst is true and will show <MySecondComponent /> if it is false.
I have a simple Next.js application that uses GraphQL to load articles from a server. Dynamic routing works perfectly fine unless you reload the page while you are on some article and want to go back.
A typical situation is completely fine
Index -> [slug] -> go back (Index)
But the issue is in this situation
[slug] -> go back(Index)
The page won't trigger rerender and while the url is pointing to Index, content on the page stays the same.
I've checked if my Link components are written correctly and they are.
This a component on Index page that contains link to redirect
const Index: FunctionComponent<IArticlePreviewProps> = (props) => {
const { article }: { article: IArticlePreviewData } = props;
return (
<Link href="/articles/[slug]" as={`/articles/${article.slug}`}>
<a>
<img src={article.thumbnail} alt=""/>
</a>
</Link>
)
}
And this is a component which is dynamic and shows article content
const Article: NextPage = (props) => {
const router = useRouter();
const { loading, data, error } = useQuery<IArticleQueryData>(ARTICLE_QUERY, {
variables: { id: router.query.slug }
});
if (loading) {
return null;
}
const article = data!.Article;
return (
<>
<div className="d-flex justify-content center">
<div className="container">
<div className="article">
<div className="article__header d-flex">
<div className="col-8 p-0 article__header-thumbnail">
<img src={article.thumbnail} alt=""/>
</div>
<div className="col-4 p-4 article__header-title d-flex flex-column justify-content-end">
<h1>{article.title}</h1>
<time className="article-date" dateTime={article.createdAt}>
{getArticlePreviewDate(article.createdAt)}
</time>
</div>
</div>
</div>
</div>
</div>
</>
)
}
It was just a bug in Next.js. It's already fixed.