fix: localStorage SSR support

This commit is contained in:
Jan Halfar 2022-01-16 22:36:37 +01:00
parent e508ddde69
commit d33307238e
2 changed files with 25 additions and 9 deletions

View File

@ -0,0 +1,12 @@
import { GoPlayground } from '../../../src/components/GoPlayground';
# yaml magic
<GoPlayground
id="2J1mp90r6nl"
proportion={16/10}
/>

View File

@ -1,8 +1,13 @@
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
const yes = "yes";
const SSR = typeof localStorage === "undefined";
if(typeof localStorage == "undefined") { const getISCool = (id) => {
var localStorage = {setItem:(name, value) => {}, getItem: (name) => {return null}}; if(typeof localStorage === "undefined") {
return false;
}
return localStorage.getItem(id);
} }
export const IsItCool = (props: { export const IsItCool = (props: {
@ -10,18 +15,17 @@ export const IsItCool = (props: {
topic: string; topic: string;
id: string; id: string;
}) => { }) => {
let defaultIsCool = false; const [isCool, setIsCool] = useState(getISCool(props.id));
if (localStorage.getItem(props.id) == "yes") { useEffect(() => {
defaultIsCool = true; console.log("well it is cool",props.id, {isCool, SSR})
} }, [isCool, SSR]);
const [isCool, setIsCool] = useState(defaultIsCool);
if (!isCool) { if (!isCool) {
return ( return (
<div> <div>
<button <button
className="button button--lg button--secondary" className="button button--lg button--secondary"
onClick={(_e) => { onClick={(_e) => {
localStorage.setItem(props.id, "yes"); localStorage.setItem(props.id, yes);
setIsCool(true); setIsCool(true);
}} }}
> >