with {:ok, %{body: body}} <- HTTPoison.get(url, headers) do
Poison.decode!(body)
end
Tho, this always returns one response, never something else. How can I randomize the response?
I tried it with Enum.random(Poison.decode!(body)) but it didnt fix the issue
I get the following response
“Name is Jill”, tho there are thousands of names in that api. When I run the function 10x, its always returning “Name is Jill”, I want to return a random name.
this is the response. When I run the fetch function a few time, its always returning a different response. I made a sub function (above) that only returns the name of that map. However, if I run that function a few times, its always the same like “Jill”, “Jill” …
Which fetch function?
The fetchData function I posted above.
There is no such concept of a sub function in elixir.
I made a separate function, that calls the fetch function and then just filters it down to the name.
And the problem is, that its returning the same thing over and over again, so I somehow have to Enum.random this, but idk where and how …
When I run the fetchData function, its returning a map with all the data, its a direct api request.
Yesterday I thought “I only need the name of that map”, so I “filtered” it down to only print the name of the map. Now I dont want to have the same results over and over, I want to randomize the name.
The API endpoint returns a list of exercises, not a single object as you sayd.
body
|> Poison.decode!()
|> Enum.random()
This should return a random individual item from that list. if this does not work, please tell us what you got instead. And do not just say “did not work” or “gave an error” but tell us the exact value or error you saw.
I assume that body |> Poison.decode!() |> Enum.random() is what gets returned from APi.fetchData/0, so [%{"name" => name} | _] can not match in the case, as Enum.random/0 returns a single random item from the enumerable passed to it. You need to change the pattern to %{"name" => name}.
Enum.random/1 operates on what already has been returned by HTTPoison it does not change the request itself.
At the time you call Enum.random/1 the request already has happened and also Poison.decode/1 has already decoded the returned body from JSON to equivalent Elixir data structures.