0

Let me first say I have a solution to this problem, but I'm interested in knowing whether there is a better way, and whether I'm doing something wrong.

I have a table of objects on the front-end of a webapp, I need to asynchronously load some data for the objects as it is needed on a per-object basis. The server returns a JSON array containing the data for that object, and the data contains the object's key, so I can update the object on the front-end with its data. When there is no data, I just get an empty array, which unfortunately presents no way of updating the object, since I don't have the key to update it with. This can result in another query later, which is a waste of time/resources. I can't modify the server, is there a way to do this nicely?

My current solution is to just set the object's data to an empty array before sending the request, then just update when the result is received if the result is nonempty.

I was wondering if there is a better/more idiomatic way to do this.

For reference, I'm using Elm with PostgREST as the backend.

4

1 回答 1

2

您可以使用柯里化和偏函数应用程序来指示应该更新哪个对象 ID。

我假设你有一些类似的代码:

type Msg
  = ...
  | FetchData Int
  | DataFetched [Data]
  | DataFetchFail Http.Error

-- inside the update function
update msg model =
  case msg of
    ...
    FetchData id =
      model ! [ Task.perform DataFetchFail DataFetched (Http.post ...) ]

如果您将DataFetched构造函数定义为包含 ID 作为第一个参数,则可以使用部分应用程序包含 ID 以供将来查找,而不管服务器返回什么。

这是与此想法相同的代码块:

type Msg
  = ...
  | FetchData Int
  | DataFetched Int [Data]
  | DataFetchFail Http.Error

-- inside the update function
update msg model =
  case msg of
    ...
    FetchData id =
      model ! [ Task.perform DataFetchFail (DataFetched id) (Http.post ...) ]

您还可以将 ID 添加到 Fail 消息中以获取更细粒度的错误消息。

于 2016-07-28T19:26:16.477 回答