1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

jotaiを初めて使う

Posted at

jotaiとは

まだあまりわかっていないのでざっくり、
状態管理めっちゃいい感じにしてくれるやつ

状態管理のライブラリは他にも下記がある

使い方

atomを作る

フォルダ構成

atoms
┣ index
┣ user
┗ team

書き方

①すべてファイル分けし、indexでまとめる方法

//index
export { userAtom } from './user'
export { teamAtom } from './team'

それぞれのファイルは初期値を記載

//user
import { atom } from 'jotai'

export const userAtom = atom({
    userData: [],
    userLoading: false,
    userError: {}
})

②すべて同一のファイルに記載

//index
import { atom } from 'jotai'

export const userAtom = atom({
    userData: [],
    userLoading: false,
    userError: {}
})

export const teamAtom = atom({
    teamData: [],
    teamLoading: false,
    teamError: {}
})

※下記のような書き方があるらしいがまだよくわかってない

  • 読み取り専用アトム
  • 書き込み専用アトム
  • 読み書き可能なアトム
const readOnlyAtom = atom((get) => get(priceAtom) * 2)
const writeOnlyAtom = atom(
  null, // it's a convention to pass `null` for the first argument
  (get, set, update) => {
    // `update` is any single value we receive for updating this atom
    set(priceAtom, get(priceAtom) - update.discount)
    // or we can pass a function as the second parameter
    // the function will be invoked,
    //  receiving the atom's current value as its first parameter
    set(priceAtom, (price) => price - update.discount)
  },
)
const readWriteAtom = atom(
  (get) => get(priceAtom) * 2,
  (get, set, newPrice) => {
    set(priceAtom, newPrice / 2)
    // you can set as many atoms as you want at the same time
  },
)

これなんか便利そうだから理解したい

hooksやページ側で使う

import { useAtom } from 'jotai'
import { userAtom } from '@/atoms'

export function useUser() {
const [user,setUser] = useAtom(userAtom)

//他の状態は変更せずuserLoadingのみ変更する
setUser(prev => ({...prev, userLoading:true}))

//使用する
if(user.userLoading)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?