How can I get element by index in array and check if he exist?

React example

Use Belt option:

module Button = {
  @react.component
  let make = () => {
    
    let (currentIndex, setCurrentIndex) = React.useState(_ => 0)
    let (cards, setCards) = React.useState(_ => [1, 2, 3])
    
    let currentCard = Belt.Array.get(cards, currentIndex)
    
    let onClick = (event) => {
      ReactEvent.Mouse.preventDefault(event);
      setCurrentIndex(prev => prev + 1);
      
    }
    
    currentCard->Belt.Option.mapWithDefault(
      React.null,
      currentCard => <button onClick>{React.int(currentCard)}</button>
    )
  }
}

Playground

Also you can use switch in returns:

    switch(currentCard) {
      | Some(currentCard) => <button onClick>{React.int(currentCard)}</button>
      | None => React.null
    }

Playground

3 Likes

You can use Belt.Array.get link which would return an optional.

    let currentCard = Belt.Array.get(cards, currentIndex)

Playground

2 Likes

myArray[i] is actually a syntax sugar for Array.get(myArray, i) so the best solution for that is just to open Belt at the top of your file so it uses Belt.Array.get instead of legacy Ocaml Array.get:

let array = [0,1,2,3]

// this will error
let error = array[6]

open Belt 

// now this returns an option
let option = array[6]

playground

8 Likes

Wow, I didn’t know that I can do this)

Interesting, thank you.

Should I always use Belt for working with Array?

It’s definitely safer, and usually more performant so I’d recommend it indeed

2 Likes