Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reusable functions that leverage Containers outside components #77

Open
colthreepv opened this issue Jun 6, 2020 · 1 comment
Open

Comments

@colthreepv
Copy link

colthreepv commented Jun 6, 2020

Let's imagine I have components with similar logic, example:

import React from 'react'
import { AppContainer } from '../container/app'
import "..."

const FileListComponent: FC = () => {
  const app = AppContainer.useContainer()

  const fetchFileList = async () => {
    let myFileList: SavedFileList
    try {
      myFileList = await fetchList()
    } catch (error) {
      return errorToast(error)
    }
    app.replaceFileList(myFileList)
  }

  return (
    <div>
    {app.fileList.map(file => (<p>{file.name}</p>))}
    </div>
  )
}

I would like to bring the function myFileList out of that, but it has typing problems:

const fetchFileList = async (app: AppContainer) => {
  let myFileList: SavedFileList
  try {
    myFileList = await fetchList()
  } catch (error) {
    return errorToast(error)
  }
  app.replaceFileList(myFileList)
}

As AppContainer is a value, not a type, and it cannot be used that way. Is there a suitable typing solution for this?

@colthreepv
Copy link
Author

A "plausible" typing I have found is the following one:

Demo: container/app.ts

export const initialApp = {
  fileList: [] as SavedFileList[]
}
export function useApp (initialState = initialApp) {
  const [fileList, setFileList] = useState(initialState.fileList)
  const replaceFileList = (files: SavedFileList[]) => setFileList(files)

  return {
    fileList,
    // methods
    replaceFileList,
  }
}

export const AppContainer = createContainer(useApp)
export type AppContainerState = ReturnType<typeof useApp>

I hope there is also a more user-friendly version

Reusable function:

const fetchFileList = async (app: AppContainerState) => {
  let myFileList: SavedFileList
  try {
    myFileList = await fetchList()
  } catch (error) {
    return errorToast(error)
  }
  app.replaceFileList(myFileList)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant