I'm having trouble understanding the correct way of handling data exchange between server-side and client-side components in NextJS 13.
I'm trying to understand this by creating the simplest scenario possible. I have these two functions that simply read and write JSON files on the server:
import fs from 'fs'
export const saveData = async (data) => {
const jsonData = JSON.stringify(data)
try {
await fs.promises.writeFile('data/data.json', jsonData)
} catch (err) {
console.log('Error', err)
}
}
export const getData = async () => {
try {
const jsonData = await fs.promises.readFile('data/data.json')
const data = JSON.parse(jsonData)
return data
} catch (err) {
console.log('Error', err)
return null
}
}
A React component that displays the data:
export const SomeComponent = ({ data }) => <p>{data.someKey}</p>
And an interactive React component that gets user input:
'use client'
import { useState } from 'react'
export default function Input({ handleInput }) {
const [value, setValue] = useState()
return (
<div>
<input type="text" onChange={(e) => setValue(e.target.value)}/>
<button onClick={() => handleInput(value)}>Save</button>
</div>
)
}
If I create a page function to get the data and handle saving new data, I cannot pass the handler to the Input component, because it's a client-side component.
import { SomeComponent } from './components/component'
import { getData, saveData } from './data'
import Input from './components/input'
export default async function Home() {
const data = await getData()
const handleInput = (data) => {
saveData(data)
}
return (
<div>
<SomeComponent data={data} />
{/* Error: */}
<Input handleInput={handleInput}/>
</div>
)
}
How, then, is passing data between the client and the server supposed to be handled in this example?