Sending json through port

Hello, first time elm user here.

I am trying to create a program that encodes some parking spot data as json and sends it through a port.

The example in the docs mention cache (E.int 42) where cache is the name of the port.

I tried to modify this slightly, my port is named spotter, but when i compile i get the following error:

Something went wrong while parsing spotter's definition.

46| spotter jason
47| 
48| main =
    ^
I was expecting to see the rest of spotter's definition. Maybe you forgot some
code? Or maybe the body of `spotter` needs to be indented?

Program is here:

port module Main exposing (..)
import Json.Encode as E
import Html as H
import Browser

-- PORTS

port spotter : E.Value -> Cmd msg

-- PARKING INFO

type alias State =
  { string : String
  , bool : Bool
  }

type alias Spot =
  { id : Int
  , longitude : Float
  , latitude : Float
  , available : State
  }

-- ENCODERS

encodeSpot : Spot -> E.Value
encodeSpot spot =
  E.object
  [ ("id", E.int spot.id)
  , ("longitude", E.float spot.longitude)
  , ("latitude", E.float spot.latitude)
  , ("available", encodeState spot.available)
  ]

encodeState : State -> E.Value
encodeState state =
  E.object
  [ ("string", E.string state.string)
  , ("bool", E.bool state.bool)
  ]

testState = State "free" True
testSpot = Spot 55 3.3 3.3 testState
jason = encodeSpot testSpot

-- send through port
spotter jason

-- placeholder main
main =
  H.text testSpot.available.string

What is wrong?

Sending data to a port is a command. You probably want to do this in your update or init function. If you’re unfamiliar with commands, check out https://guide.elm-lang.org/effects/

The code will probably look something like:

update : Msg -> State -> (State, Cmd Msg)
update msg state =
  case save of
    SaveState ->
       (model, spotter (encodeState state))

It looks like you are trying to use Elm as an imperative language. In elm, you cant just have it run something by calling a function outside of a function definition. If you want to actually be able to do something in your program, you cant use static html as your main value

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.