Estoy creando un componente de comentarios en el que obtengo datos de un archivo json almacenado localmente. Importo los datos en los datos variables y establezco sus campos correspondientes a mis valores de estado. Pero cuando paso los datos a través del contexto, dice que no está definido.
datos.json
{ "currentUser": { "image": { "png": "./images/avatars/image-juliusomo.png", "webp": "./images/avatars/image-juliusomo.webp" }, "username": "juliusomo" }, "comments": [ { "id": 1, "content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.", "createdAt": "1 month ago", "score": 12, "user": { "image": { "png": "./images/avatars/image-amyrobson.png", "webp": "./images/avatars/image-amyrobson.webp" }, "username": "amyrobson" }, "replies": [] } ] }así es como almaceno y paso datos context.js
import data from "./data"; const AppContext = React.createContext(); const AppProvider = ({ children }) => { const { comments, setComments } = useState(data.comments); const { currUser, setCurrUser } = useState(data.currentUser); return ( <AppContext.Provider value={{ comments, currUser }}> {children} </AppContext.Provider> ); };aquí es donde obtengo el error App.js
import { useGlobalContext } from "./context"; const App = () => { const { comments, currUser } = useGlobalContext(); ... }El gancho useState devuelve una matriz, no un objeto. Se utiliza la asignación de desestructuración de matriz. El primer elemento es el valor de estado, el segundo es la función de actualización de estado.
const AppProvider = ({ children }) => { const [comments, setComments] = useState(data.comments); const [currUser, setCurrUser] = useState(data.currentUser); return ( <AppContext.Provider value={{ comments, currUser }}> {children} </AppContext.Provider> ); };