I'm attempting to display/format a datetime counter in NextJS but am encountering hydration issues. The following should work, no?
next-dev.js?3515:24 Warning: Text content did not match. Server: "01:07:28" Client: "01:07:29"
import { useRef, useState, useEffect } from "react";
function MyApp({ Component, pageProps }) {
const [currentTime, setCurrentTime] = useState(() => {
const hour = ("0" + new Date().getUTCHours()).slice(-2);
const minutes = ("0" + new Date().getUTCMinutes()).slice(-2);
const seconds = ("0" + new Date().getUTCSeconds()).slice(-2);
return `${hour}:${minutes}:${seconds}`;
});
return (
<span>
{currentTime}
</span>
);
}
export default MyApp;
Related
I am working on a new project, and recently used nextjs13 for my frontend application.
When using the function generateStaticParams with the next/header library function headers(),
I get an error in dev mode.
Error occured during dev mode
But when the frontend is on using next build / next start, the error does not appear.
The main reason I am using the next/header library is due to next-auth, to gain access to cookies.
generateStaticParams is in the app/detail/[questionId]/page.tsx file
next/headers is in app/layout.tsx file
app/page.tsx
import React from "react";
import QuestionCard from "../components/Card/QuestionCard";
import Carousel from "../components/Carousel/Carousel";
import HomeNavBar from "../components/HomeNavBar/HomeNavBar";
import { ICarousel } from "../types/carousel";
import TabNavigator from "../components/TabNavigator/TabNavigator";
const getGoogleSession = async () => {};
const getQuestionList = async () => {
const response = await fetch(`https://pioneroroom.com/questionlist`);
const data = await response.json();
return data;
};
const page = async ({ Question }: any) => {
// const imageArr = await getCarouselImages();
const data = await getQuestionList();
return (
<div className="main">
<HomeNavBar />
{/* <Carousel carousel={imageArr} /> */}
<div className="contentbody">
{data.data.map((e: any) => {
return <QuestionCard key={e.questionId} question={e} />;
})}
</div>
<TabNavigator activeLink={""} />
</div>
);
};
export default page;
app/layout.tsx
import { Roboto, Noto_Sans_KR } from '#next/font/google';
import NavBar from '../components/HomeNavBar/HomeNavBar';
import '../styles/globals.css';
import SessionContainer from '../components/Providers/SessionProvider';
import '../styles/globals.css';
import { unstable_getServerSession } from 'next-auth';
import { getSession } from '../utils/helper/session';
import { cookies, headers } from 'next/headers';
import HomeNavBar from '../components/HomeNavBar/HomeNavBar';
import TabNavigator from '../components/TabNavigator/TabNavigator';
const noto = Noto_Sans_KR({
weight: '400',
fallback: ['Roboto'],
subsets: ['latin'],
});
const RootLayout = async ({ children }: any) => {
const { segment } = children.props.childProp;
const session = await getSession(headers().get('cookie') ?? '');
const nextCookies = cookies();
return (
<html className={noto.className}>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>asdf</title>
</head>
<body>
<SessionContainer session={session}>{children}</SessionContainer>
</body>
</html>
);
};
export default RootLayout;
app/detail/[questionId]/page.tsx
import { headers } from 'next/headers';
import React, { use } from 'react';
import { getSession } from '../../../utils/helper/session';
const fetchPost = async (id: any) => {
const res = await fetch(`https://pioneroroom.com/questionlist/${id}`);
return await res.json().then((res) => res.data);
};
const DetailIdPage = async ({ params }: any) => {
console.log('params.questionId', params.questionId);
const post = await fetchPost(params.questionId);
return (
<div>
<p>{JSON.stringify(post)}</p>
</div>
);
};
// BUG: generateStaticParams 함수가 현재 dev 모드에서 동작하지 않음.
// dynamic headers( next/headers )의 cookie등을 불러올 때 오류를 일으키고,
// dev mode에서 이 함수와 결합하여 사용하면 dynamic server usage: headers error 발생함.
/*
export async function generateStaticParams() {
const res = await fetch('https://pioneroroom.com/questionlist');
const data = await res.json();
const arr = data.data.map((e: any) => {
console.log('map', e.questionId);
return {
questionId: String(e.questionId),
};
});
return arr;
}
*/
export default DetailIdPage;
Erasing either both of the code (generateStaticParams or next/header) solves the problem. No errors occuring in dev mode.
Hello I'm using firebase for the first time, I want to upload a file (video or image) to firebase but I keep getting error 400
I'm using react native
import { storage_bucket } from '../firebase';
import { ref,uploadBytesResumable } from "firebase/storage";
import { View, Text } from 'react-native'
import React from 'react'
export default function test() {
const uploadVideo = (e) => {
let file = e.target.files[0];
let fileRef = ref(storage_bucket,file.name);
const uploadTask = uploadBytesResumable(fileRef,file);
uploadTask.on('state_changed',(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('uplaod is' + progress + '% done');
})
}
return (
<View>
<input type="file" onChange={uploadVideo}></input>
</View>
)
}
Using Next.js, I can get the context value in header.js file without a problem but it returns undefined in _app.js
Here is my code.
useLang.js
import { createContext, useContext, useState } from 'react'
const LangContext = createContext()
export const LangProvider = ({ children }) => {
const [lang, setLang] = useState('en')
const switchLang = (selected) => setLang(selected)
return (
<LangContext.Provider value={{ lang, switchLang }}>
{children}
</LangContext.Provider>
)
}
export const useLang = () => useContext(LangContext)
_app.js
import { LangProvider, useLang } from '../hooks/useLang'
export default function MyApp(props) {
const { Component, pageProps } = props
const contexts = useLang()
console.log(contexts) // ------> undefined. why ???
return (
<LangProvider>
<Component {...pageProps} />
</LangProvider>
)
}
header.js
import { useLang } from '../hooks/useLang'
export default function Header() {
const { lang } = useLang() // ------> works fine here!
return <> {lang} </>
}
I've looked at the Next.js documentation, but nowhere does it mention that you cannot use the state or context in _app.js. Any help would be appreciated.
Yes, you can not get the value of context on _app.js because on top _app.js mustn't children of LangProvider. You just only can use context's value on children component of LangProvider container.
This Meteor client code prints into is undefined to the console. It is expected to print the value of the info.description property passed to the composeWithTracker(composer)(Info) at the bottom of the code.
Where did I go wrong? Thanks
//--------------- carInfo.jsx ---------------
import React from 'react';
const renderWhenData = ( info ) => {
console.log( 'info is ' +info); //<<<<<<<<<<<<<<<<<<< undefined
if ( info ) {
return <span>{ info.description }</span>;
};
export let Info = ( { info } ) => (
<p>{ renderWhenData( info ) }</p>
);
//--------------- carClass.jsx ---------------
import React from 'react';
import ReactDOM from 'react-dom';
import { composeWithTracker } from 'react-komposer';
import { Info } from '../ui/carInfo.jsx';
const composer = (props, onData) => {
const subscription = Meteor.subscribe('vehicles');
if (subscription.ready()) {
const cars = Vehicles.findOne({name: 'Jack'}); //<<<<<<<<<<<<<<< document OK.
onData(null, { cars });
}
};
const Container = composeWithTracker(composer)(Info);
ReactDOM.render(<Container />, document.getElementById('react-info'));
This Meteor React code is producing browser console error:
Warning: ListItems(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
Exception from Tracker recompute function:
Any idea why? Thanks
//myList.jsx
import React from 'react';
const renderIfData = (listItems) => {
if (listItems && listItems.length > 0) {
return listItems.map((item) => {
return <li key={item._id}>{item.car}</li>;
});
} else {
return <p> No cars yet!</p>
}
};
export const ListItems = ({listItems}) => {
<ol>{renderIfData(listItems)}</ol>
};
//cars.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { composeWithTracker } from 'react-komposer';
import { ListItems } from '../imports/ui/myList.jsx';
import { CarsCol } from '../imports/api/collections.js';
const composer = (props, onData) => {
const sub = Meteor.subscribe('carsCol');
if (sub.ready()) {
const cars = CarsCol.find().fetch();
onData(null, {cars});
}
};
const Container = composeWithTracker(composer) (ListItems);
ReactDOM.render(<Container />, document.getElementById('react-root'));
Everything looks nice except this part:
return listItems.map((item) => {
return <li key={item._id}>{item.car}</li>;
});
The result of this operation is an array of elements, and React discourages it with exactly the kind of error you're receiving. In fact, in React 16, they promise to allow this, but you're likely using version 15. Anyway, I'd recommend returning a single root element everywhere, so the whole thing would look like
//myList.jsx
import React from 'react';
export const ListItems = ({listItems}) => {
if (listItems && listItems.length > 0) {
return (
<ol>
{listItems.map((item) => (
<li key={item._id}>{item.car}</li>
))}
</ol>
);
} else {
return (
<p>No cars yet!</p>
);
}
};
//cars.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { composeWithTracker } from 'react-komposer';
import { ListItems } from '../imports/ui/myList.jsx';
import { CarsCol } from '../imports/api/collections.js';
const composer = (props, onData) => {
const sub = Meteor.subscribe('carsCol');
if (sub.ready()) {
const cars = CarsCol.find().fetch();
onData(null, {cars});
}
};
const Container = composeWithTracker(composer) (ListItems);
ReactDOM.render(<Container />, document.getElementById('react-root'));