Answer the question
In order to leave comments, you need to log in
Why does static data disappear after the component is redrawn?
I am using nextjs and generating statics with getStaticProps. Then I pass them to the corresponding component through props, and then after the component is redrawn (I change the screen size), the data becomes empty. How to save them if useState doesn't help?
//index.js
import React from 'react'
const AsyncCustomers = dynamic(() => import('~/components/customers/Customers'))
const HomePage = (props) => {
return(
<Layout>
<AsyncCustomers customers={props.customers}/>
</Layout>
)}
export default HomePage
export const getStaticProps = async () => {
const customers = await fetch(process.env.API_SERVER + 'customers')
return {
props: {
customers : await customers.json(),
},
}
}
//Customers.js
import React, {useState, useEffect, useLayoutEffect} from 'react'
import { getWindowDimensions } from '~/core/helpers/utils'
const getPageCount = () => {
const [count, setPageCount] = useState(1)
const handleResize = () => {
let width = getWindowDimensions().width
let n = (width < 576) ? 1 : (width < 768) ? 2 : (width < 992) ? 3 : 4
setPageCount(n)
}
useLayoutEffect(() => {
handleResize()
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
},[])
return count
}
const Customers = ({customers}) => {
const [array, setArray] = useState([]) //хранение массива customers для использования после изменения счетчика страниц
const [customersFormatted, setCustomersFormatted] = useState([]) // хранение обновленного масива заказчиков, разбитого на страницы
const [pageCount, setCount] = useState(1)
const count = getPageCount() // получаю количество страниц с клиентами
if (pageCount != count) {
setCount(count)
}
useEffect(() => {
setArray(customers) //<--- здесь данные сохраняются
},[])
useEffect(() => {
console.log(array); // <--- здесь массив уже пустой после изменения счетчика страниц
setCustomersFormatted(Array(Math.ceil(array.length/pageCount)).fill().map(_ => array.splice(0, pageCount)))
},[pageCount])
return (customersFormatted.length > 0 &&
<Section>
{customersFormatted.map((row, index) => (
<div key={`row-${index}`} className="row">
<Items customers={row} />
</div>
))}
</Section>
)}
export default Customers
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question